C pointer addition

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

In the previous lecture we have learnt about decrementing pointer variable. In this chapter we will be learning about adding integer number to pointer variable.

Adding integer value with Pointer

In C Programming we can add any integer number to Pointer variable. It is perfectly legal in c programming to add integer to pointer variable.
In order to compute the final value we need to use following formulae :

final value = (address) + (number * size of data type)

Consider the following example –

int *ptr , n;
ptr = &n ;
ptr = ptr + 3;

Live Example 1 : Increment Integer Pointer

#include<stdio.h>

int main(){

int *ptr=(int *)1000;

ptr=ptr+3;
printf("New Value of ptr : %u",ptr);

return 0;
}

Output :

New Value of ptr : 1006

Explanation of Program :

In the above program –

int *ptr=(int *)1000;

this line will store 1000 in the pointer variable considering 1000 is memory location for any of the integer variable.

Formula :

ptr = ptr   + 3 * (sizeof(integer))
    = 1000  + 3 * (2)
    = 1000  + 6
    = 1006

Similarly if we have written above statement like this –

float *ptr=(float *)1000;

then result may be

ptr = ptr   + 3 * (sizeof(float))
    = 1000  + 3 * (4)
    = 1000  + 12
    = 1012

In the next chapter we will be subtracting the integer number from the pointer variable.