Vous êtes sur la page 1sur 97

COURSE

Computer Programming
By
Ms. Varpe kanchan
POINTERS
in
C Programming
By
Ms. Varpe Kanchan

http://www.c4learn.com/index/pointer-c-programming/
Outline
 C Pointer Expression For A[i][j], Pointer Arithmetic Operations
 Pointer To Constant Objects
 C Pointer  Incrementing Pointer  Constant Pointers
 C Pointer Basic Concept  Pointer Addition  Pointer To Array Element
 Pointer Address Operator  Decrementing Pointer  Pointer To Array Of String
 Function Pointer
 Pointer Memory Organization  Subtracting Integer Value From Pointer
 Function Pointer Reference
 Pointer Variable Memory  Subtracting
Required Pointers
 Pointer To Array Of Function
 Size Of Pointer Variable  Comparing Two Pointer Variables
 Size Of Const Pointer
 Pointer Operator  Pointer Operation Rules  Accessing Integer Using Char
 Pointer Invalid Operations Pointer
 Pointer Declaration
 Null Pointer
 Precedence Of * And & Operator
 Initialization Of Pointer  Difference Char *A Vs Char A[]
 Meaning Of (*++Ptr) Pointer
 Dereferencing Pointer  Reading Complex Pointer
 Meaning Of (++*Ptr) Pointer Expression
 Void Pointers
 Difference Between *Ptr++ & ++*Ptr  Pointer Mistakes
 Dereferencing Void Pointer  Dangling Pointer
 Double Pointer Example
 Size Of Void Pointer  Pointer Application
 Double Pointer
What is a pointer?
 a simple integer variable which holds a memory address that
points to a value, instead of holding the actual value itself.
 The computer's memory is a sequential store of data, and a
pointer points to a specific part of the memory.
 Our program can use pointers in such a way that the pointers
point to a large amount of memory - depending on how much we
decide to read from that point on.

& symbol is used to get address of variable


* symbol is used to get value from the address given
by pointer.
https://www.learn-c.org/en/Pointers
Role of pointer:
 Pointers are also variables and play a very important role in C
programming language. They are used for several reasons, such
as:
 Strings
 Dynamic memory allocation
 Sending function arguments by reference
 Building complicated data structures
 Pointing to functions
 Building special data structures (i.e. Tree, Tries, etc...)
 And many more.

https://www.learn-c.org/en/Pointers
C Pointer Basics

Consider above Diagram which clearly shows pointer


concept in c programming –
1. i is the name given for particular memory location
of ordinary variable.
2. Let us consider it’s Corresponding address be
65624 and the Value stored in variable ‘i’ is 3
3. The address of the variable ‘i’ is stored in another
integer variable whose name is ‘j’ and which is
having corresponding address 65522
C Pointer Basics (1)
C Pointer Basics (2)
Understanding pointers in c ?
 We know that –
 Pointer is a variable which stores the address of another variable
 Since Pointer is also a kind of variable , thus pointer itself will be
stored at different memory location.

 2 Types of Variables :
 Simple Variable that stores a value such as integer,float,character
 Complex Variable that stores address of simple variable i.e pointer
variables
Understanding pointers in c ?
Understanding pointers in c ?
Pointer Address Operator

1.Pointer address operator is denoted by,


‘&’ symbol
2.When we use ampersand symbol as a prefix to a
variable name ‘&’, it gives the address of that
variable.
lets take an example –
&n - It gives an address on variable n
Pointer Address Operator

to print the address of the variable we use

ampersand along with %u


Understanding Pointer Address Operator
Invalid Use of Pointer Address Operator

 &75

 &('a')

&(a+b)
Pointer Variable Memory Required
 When we use variable in program then Compiler
keeps some memory for that variable depending on
the data type
 The address given to the variable is Unique with
that variable name
 When Program execution starts the variable name
is automatically translated into the corresponding
address.
C pointer variable memory required
 How much Memory required to store Pointer variable?
 Pointer Variable Stores the address of the variable
 Variable may be integer, character, float but the address of the
variable is always integer so Pointer requires 2 bytes of memory in
Turbo C Compiler.
 If we run same program in any other IDE then the output may differ.
 This requirement is different for different Compilers
C pointer variable memory required
C pointer variable memory required
C size of pointer variable
 Pointer is the variable that stores the address of
another variable.
 Size calculation
 Consider the following memory map before
declaring the variable. In the memory comprise
of blocks of 1 byte.
 Whenever we declare any variable then
random block of memory is chosen and value
will be stored at that memory location.
 Similarly whenever we declare any pointer
variable then random block of memory will be
used as pointer variable which can hold the
address of another variable.
C size of pointer variable
Pointer Operator
Pointer Operator Example
HOW Pointer Operator Works?
What Pointer Declaration tells to Compiler
C pointer declaration
Ways of C pointer variable declaration
Initialization of pointer
Initialization of pointer
Example: Initialization of pointer
Dereferencing Pointer
 Asterisk(*) indirection operator is used along with pointer
variable while Dereferencing the pointer variable.
 Asterisk Operator is also called as value at operator
 When used with Pointer variable, it refers to variable being
pointed to, this is called as Dereferencing of Pointers
 Dereferencing Operation is performed to access or manipulate
data contained in memory location pointed to by a pointer
 Any Operation performed on the de-referenced pointer
directly affects the value of variable it pointes to.
Dereferencing Pointer Example
Void Pointers
 Definition:
 Suppose we have to declare integer pointer, character pointer
and float pointer then we need to declare 3 pointer
variables.
 Instead of declaring different types of pointer variable it is
feasible to declare single pointer variable which can act as
integer pointer, character pointer.
Void Pointers Basics
Void Pointers Declaration & Example
Dereferencing Void Pointer

Why it is necessary to use Void Pointer ?


Reason : Re-usability of Pointer
Dereferencing Void Pointer Example
Dereferencing
Void Pointer
Example
Size of Void Pointer
Size of Void Pointer Example
Pointer Arithmetic Operations
Pointer Arithmetic Operations
Incrementing Pointer
 Incrementing Pointer is generally used in array because we
have contiguous memory in array and we know the contents of
next memory location.
 Incrementing Pointer Variable Depends Upon data type of the
Pointer variable
Incrementing Pointer Example
Incrementing Pointer Example
Pointer Addition
Pointer Addition
Decrementing Pointer
Decrementing Pointer
Subtracting Integer Value From Pointer
 Suppose we have subtracted
“n” from pointer of any data type
having initial address as
“init_address” then after
subtraction we can write –
Subtracting Pointers
 Differencing Means Subtracting two Pointers.
 Subtraction gives the Total number of objects between them .
 Subtraction indicates “How apart the two Pointers are ?”
Subtracting Pointers
Comparing Two Pointer Variables
 Pointer comparison is Valid only if the two pointers are Pointing
to same array
 All Relational Operators can be used for comparing pointers of same
type
 All Equality and Inequality Operators can be used with all Pointer
types
 Pointers cannot be Divided or Multiplied
Comparing Two Pointer Variables
Note:
 Ptr1 assigned value as address 1000
 Ptr2 assigned value as address 2000
 &ptr1 and &ptr2 gives pointer self
address
 Printing ptr1 and ptr2 will output
values stored in pointer i.e. 1000 and
2000
 But
 Value at address 1000 and 2000 not
available hence it will give
 Segmentation fault error for *ptr1 and
*ptr2
Comparing Two Pointer Variables
Divide and Multiply Pointer
Pointer Operation Rules
Pointer Operation Rules
Pointer Operation Rules
Pointer Invalid Operations
 some more arithmetic operations that cannot be performed on pointer –
 Addition of two addresses.
 Multiplying two addresses.
 Division of two addresses.
 Modulo operation on pointer.
 Cannot perform bitwise AND,OR,XOR operations on pointer.
 Cannot perform NOT operation or negation operation.

 For more details


 http://www.c4learn.com/c-programming/c-pointer-invalid-operations/
Precedence Of * And & Operator
 Precedence of Value at Operator :
 Value at operator is denoted by ‘*’.
 In C Star(*) operator is used for two purposes –
 Multiplication
 In Pointer for De-referencing

 Some important points about De-Reference Operator :


 Value at Operator (*) is unary operator when use in pointer.
 Multiplication Operator (*) is binary operator when used for
multiplication.
 Value at operator ‘*’ in pointer concept is also called as “De-reference”
Operator Or “Value at Operator“
Precedence Of * And & Operator
 Precedence of ‘ * ‘ and ‘ & ‘ Operator
 Both are Unary Operators
 They have Equal Precedence
 They Associate from Right –> Left
Meaning of (*++ptr) pointer

Explanation :
1. ‘++’ and ‘*’ both have Equal Precedence
2. Associativity is from Right to Left ( Expression evaluated from R->L)
3. Both are Unary (Operates on single operand )
4. So ‘ ++ ‘ is Performed First then ‘ * ‘
Meaning of (*++ptr) pointer
Meaning of (*++ptr) pointer
 This operation should not be used in normal operation.
 Perform this operation if we have consecutive memory
i.e Array.
 If we perform this operation in above example then we
will get garbage value as we don't know the value stored
at 3060.
 Consider following example to get idea , how *++ptr is
used in Array –
Meaning of (*++ptr) pointer: Example
Meaning of (++*ptr) pointer

Explanation : Meaning of (++*ptr) pointer


1. ‘++’ and ‘*’ both are having equal precedence and priority.
Associativity of these two operators is from right to left
(Expression evaluated from R->L)
2. Both the operators are Unary so they will only works on single
operand
3. Dereference operator ‘*’ will get chance for execution before pre
increment operator ‘++’.
Meaning of (++*ptr) pointer
Meaning of (++*ptr) pointer
Question : Are *ptr++ and ++*ptr are same ?
Ans : Absolutely Not

*ptr++ means
Increment the Pointer not Value Pointed by It
++*ptr means
Increment the Value being Pointed to by ptr
Are ++*ptr and *ptr++ are same ?
Are ++*ptr and *ptr++ are same ?
C Double Pointer Example
Pointer to Pointer (Double Pointer)
 Double (**) is used to denote the double
Pointer
 Pointer Stores the address of the Variable
 Double Pointer Stores the address of the
Pointer Variable
Pointer to Pointer (Double Pointer) - Example
Dynamic Memory Allocation

https://www.guru99.com/c-dynamic-memory-allocation.html
How Memory Management in C works?
 When you declare a variable using a basic data type, the C compiler
automatically allocates memory space for the variable in a pool of
memory called the stack.
 For example, a float variable takes typically 4 bytes (according to the
platform) when it is declared.
 We can verify this information using the sizeof operator as shown in
below example
#include <stdio.h>
int main() {
float x;
printf("The size of float is %d bytes", sizeof(x));
return 0; }
 The output will be: The size of float is 4 bytes
How Memory Management in C works?
 An array with a specified size is allocated in contiguous blocks of memory, each
block has the size for one element:
#include <stdio.h>
int main()
{ float arr[10];
printf("The size of the float array with 10 element is %d", sizeof(arr));
return 0;}
 The result is: The size of the float array with 10 element is 40
 As learned so far, when declaring a basic data type or an array, the memory is
automatically managed.
 However, there is a process for allocating memory which will permit you to
implement a program in which the array size is undecided until you run your
program (runtime).
 This process is called "Dynamic memory allocation."
Dynamic memory
 An aspect of allocating and freeing memory according
to your needs.
 Dynamic memory is managed and served with pointers
that point to the newly allocated space of memory in an
area which we call the heap.
 Now you can create and destroy an array of elements
at runtime without any problems.
 To sum up, the automatic memory management uses
the stack, and the dynamic memory allocation uses
the heap.
Dynamic Memory
 The <stdlib.h>, <alloc.h> (Turbo C) library has functions responsible for dynamic
memory management.
The malloc Function
• The malloc() function stands for memory allocation.
• Used to allocate a block of memory dynamically.
• It reserves memory space of specified size and returns the null pointer
pointing to the memory location.
• The pointer returned is usually of type void.
• It means that we can assign malloc function to any pointer.
• Syntax
ptr = (cast_type *) malloc (byte_size);
• Here, ptr is a pointer of cast_type.
• The malloc function returns a pointer to the allocated memory of
byte_size.
• Example: ptr = (int *) malloc (50)
• When this statement is successfully executed, a memory space of 50 bytes
is reserved. The address of the first byte of reserved space is assigned to
the pointer ptr of type int.
The malloc Function
The free Function
• The memory for variables is automatically deallocated at
compile time.
• In dynamic memory allocation, you have to deallocate memory
explicitly.
• If not done, you may encounter out of memory error.
• The free() function is called to release/deallocate memory.
• By freeing memory in your program, you make more available
for use later.
void free(void *ptr);
• When free () is used for freeing memory allocated by malloc () or
realloc (),the whole allocated memory block is released.
• For the memory allocated by function calloc () also all the segments of
memory allocated by calloc () are de-allocated by free ().
The free Function
For example:
The calloc Function
• The calloc function stands for contiguous allocation.
• This function is used to allocate multiple blocks of memory.
• It is a dynamic memory allocation function which is used to allocate
the memory to complex data structures such as arrays and
structures.
• Malloc function is used to allocate a single block of memory space
while the calloc function is used to allocate multiple blocks of
memory space.
• Each block allocated by the calloc function is of the same size.
The calloc Function
• Syntax:
ptr = (cast_type *) calloc (n, size);
• The above statement is used to allocate n memory blocks of
the same size.
• After the memory space is allocated, then all the bytes are
initialized to zero.
• The pointer which is currently at the first byte of the
allocated memory space is returned.
• Whenever there is an error allocating memory space such as
the shortage of memory, then a null pointer is returned.
The calloc Function
calloc vs. malloc: Key Differences
• The calloc function is generally more suitable and efficient
than that of the malloc function.
• While both the functions are used to allocate memory space,
calloc can allocate multiple blocks at a single time.
• You don't have to request for a memory block every time.
• The calloc function is used in complex data structures
which require larger memory space.
• The memory block allocated by a calloc function is always
initialized to zero while in malloc it always contains a
garbage value.
The realloc Function
• you can add more memory size to already allocated
memory.
• It expands the current block while leaving the original
content as it is.
• realloc stands for reallocation of memory.
• realloc can also be used to reduce the size of the previously
allocated memory.

Syntax : ptr = realloc (ptr,newsize);

• The above statement allocates a new memory space with a


specified size in the variable newsize.
The realloc Function
• After executing the function, the pointer will be
returned to the first byte of the memory block.
• The new size can be larger or smaller than the previous
memory.
• We cannot be sure that if the newly allocated block will
point to the same location as that of the previous
memory block.
• This function will copy all the previous data in the new
region.
• It makes sure that data will remain safe.
The realloc Function

Whenever the realloc results in an unsuccessful operation, it returns a


null pointer, and the previous data is also freed.
Dynamic Arrays
• A Dynamic array allows the number of elements to grow as needed.
• They are widely used in Computer science algorithms.
• in the following program, we create and resize an array dynamically
C Pointer Expression For A[i][j]
C Pointer Expression For A[i][j] (1)
C Pointer Expression For A[i][j] (2)
C Pointer Expression For A[i][j] (3)
Thank You

Vous aimerez peut-être aussi