Search code examples
cpointersmemorygarbage

In this below C code related to pointers and its output, then why doesn't the value a[1] i.e 20 get stored at consecutive address de9?


In the Below code , each location can hold 32 bit signed data. So, why doesn't the value a1 i.e 20 get stored at consecutive address de9? Array should store the data at consecutive memory location right? I know that the sizeof(int) in this online gdb compiler is 4 bytes but how can it be related to the storing of 20 at 4 locations away? Am I missing some basic concepts?

  int main()
    {
     int a[2]= {214748368,20};
       
       void *ptr1 = &a;
       void *ptr2= &a;
       
       ptr1++;
       ptr2 = ptr2;
       
       printf("%d \n", *(int*)ptr2);
       printf("\n Pointer table");
       printf("\n Data : %d at address : %p", *(int*)ptr2, ptr2);
       ptr2=ptr2+1;
       printf("\n Data : %d at address : %p", *(int*)ptr2, ptr2);
       ptr2=ptr2+1;
       printf("\n Data : %d at address : %p", *(int*)ptr2, ptr2);
       ptr2=ptr2+1;
       printf("\n Data : %d at address : %p", *(int*)ptr2, ptr2);
       ptr2=ptr2+1;
       printf("\n Data : %d at address : %p", *(int*)ptr2, ptr2);
       return 0;
    }

Code Output


Solution

  • When you increase a pointer in C pointer arithmetic is used. So if your pointer a is of type int * it will be increased by sizeof(int). However your pointer is of type void *. This is not intended, apparently it is increased by one byte (see here).

    As the size of an int on your system is 32 bits or 4 bytes you have to increase the pointer four times by one byte to reach the next element in your array.

    You can avoid this issue by defining your pointers as int *:

    int *ptr1 = &a;
    int *ptr2 = &a;
    

    In this case incrementing the pointer once (ptr2++) will give you the next element.