Note : 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 : Incrementing Pointer Variable Depends Upon -
- data type of the Pointer variable
Formula : ( After incrementing )
new value = current address + i * size_of(data type)
Three Rules should be used to increment pointer -
Address + 1 = Address Address++ = Address ++Address = Address
Pictorial Representation :
Data Type | Older Address stored in pointer | Next Address stored in pointer after incrementing (ptr++) |
int | 1000 | 1002 |
float | 1000 | 1004 |
char | 1000 | 1001 |
Explanation : Incremeting Pointer
- Incrementing a pointer to an integer data will cause its value to be incremented by 2 .
- This differs from compiler to compiler as memory required to store integer vary compiler to compiler
Note to Remember
Increment and Decrement Operations on pointer should be used when we have Continues memory (in Array).
Live Example 1 : Increment Integer Pointer
#include<stdio.h> int main(){ int *ptr=(int *)1000; ptr=ptr+1; printf("New Value of ptr : %u",ptr); return 0; }
Output :
New Value of ptr : 1002
Live Example 2 : Increment Double Pointer
#include<stdio.h> int main(){ double *ptr=(double *)1000; ptr=ptr+1; printf("New Value of ptr : %u",ptr); return 0; }
Output :
New Value of ptr : 1004
Live Example 3 : Array of Pointer
#include<stdio.h> int main(){ float var[5]={1.1f,2.2f,3.3f}; float(*ptr)[5]; ptr=&var; printf("Value inside ptr : %u",ptr); ptr=ptr+1; printf("Value inside ptr : %u",ptr); return 0; }
Output :
Value inside ptr : 1000 Value inside ptr : 1020
Address of ptr[0] = 1000
We are storing Address of float array to ptr[0]. -
Address of ptr[1] = Address of ptr[0] + (Size of Data Type)*(Size of Array) = 1000 + (4 bytes) * (5) = 1020
Address of Var[0]…Var[4] :
Address of var[0] = 1000 Address of var[1] = 1004 Address of var[2] = 1008 Address of var[3] = 1012 Address of var[4] = 1016
You may like this
- Incrementing Pointer
- Decrementing Pointer
- Adding number to Pointer
- Subtracting number from pointer
- Differencing
- Comparing two pointers
- Illegal Arithmetic Operations that should be avoided while using Pointer