Search code examples
cpointersmemorymemory-address

What is happening with the pointer in this C code?


QUESTION->

#include<stdio.h>
    int main()
    {
        int a,*b,**c,***d;
        int x;
        a=&x;
        b=&a;
        c=&b;
        d=&c;
        printf("%d\t%d\t%d\t%d",a,b,c,d);
        a++;
        b++;
        c++;
        d++;
        printf("\n%d\t%d\t%d\t%d",a,b,c,d);
        return 0;
    }

OUTPUT

-760636132  -760636128  -760636120  -760636112

-760636128  -760636120  -760636112  -760636104

Why after 2nd pointer all the pointers increment by a value of 8?


Solution

  • If you checked you would find sizeof(int) == 4 and sizeof(int*) == 8. When you print the pointer you see the actual value. Incrementing the pointer adds the size of what the pointer points to.

    You are very close to undefined behavior. If you tried to read what these pointers pointed to (or worse, write to them), the results could be very bad.