C incrementing pointer

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Incrementing Pointer :

  1. Incrementing Pointer is generally used in array because we have contiguous memory in array and we know the contents of next memory location.
  2. 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

[box]Note to Remember : Increment and Decrement Operations on pointer should be used when we have Continues memory (in Array).[/box]

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

http://img.c4learn.com/2010/01/pointer1.jpg

Explanation :

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

In the next chapter we will be looking into more pointer operations such as Incrementing Pointer | Decrementing Pointer

[box]External Link from Wikipedia : Computer Programming C Pointers[/box]