Search code examples
cpointerspointer-arithmetic

Why memory address contained by pointer +1 is different from address of value being pointed + 1


Pointer stores memory address of value being pointed at so memory address contained by pointer is same as memory address of value. So adding 1 to both these memory addresses should yield same result, which is not happening. Why? Here is the code

 int main()
 {
     int ages[] = {23, 43, 12, 89, 2};
     int *cur_ages = ages;

     printf("\n&cur_ages=%p, &cur_ages+1=%p", &cur_ages, &cur_ages+1);
     printf("\n&ages=%p, &ages+1=%p", &ages, &ages+1);
     printf("\ncur_ages=%p, cur_ages+1=%p", cur_ages, cur_ages+1);
     printf("\n*cur_ages=%d, *cur_ages+1=%d", *cur_ages, *(cur_ages+1));

     return 0;
 }

Output is

&cur_ages=0x1ffff85f3d0, &cur_ages+1=0x1ffff85f3d8
&ages=0x1ffff85f3dc, &ages+1=0x1ffff85f3f0
cur_ages=0x1ffff85f3dc, cur_ages+1=0x1ffff85f3e0
*cur_ages=23, *cur_ages+1=43

&ages+1 is not equal to cur_ages+1. Why?


Solution

  • Pointer arithmetic increases the value of a pointer by the given value multiplied by the size of the type it points to.

    So when you do this:

    &ages+1
    

    You take the address of ages (which is of type int [5]) and add sizeof(ages) to the pointer value. Assuming sizeof(int) is 4, this adds 20 to the pointer value.

    Likewise, when you do this:

    cur_ages+1
    

    Here, cur_ages points to a int, so adding 1 adds sizeof(int) to the pointer value.