0

I was messing around with double pointers last day and this behaviour wasn't not expected:

int main(){
   char arr[2][10] = {"Burger", "Pizza"};
   char **ptr = (char**) arr;

   printf("%p %p\n", arr, ptr); // first printf
   printf("%p %p\n", arr+1, ptr+1); // second
   printf("%p %p\n", arr[0], *ptr); // third

   puts(ptr);
   puts(ptr+1);

}

In this example, I've assumed that, arr and ptr points to the same address and this assumption was confirmed correct with the first printf:

0x7fffe4fd5010 0x7fffe4fd5010

Secondly, I've assumed that, arr+1 and ptr+1, also both points to the same address, but when I tried running it, the output wasn't:

0x7fffe4fd501a 0x7fffe4fd5018

How could this be? Is there something I'm missing with the C programming language?

Spade 000
  • 109
  • 1
  • 11
  • Because they are pointing to different types, and so adding 1 adds a different amount. You had to make a cast for the compiler not to complain. – Weather Vane Oct 20 '20 at 13:36
  • For a visualizing the difference you might also see my old answer [here](https://stackoverflow.com/a/18440456/440558). – Some programmer dude Oct 20 '20 at 13:36
  • 1
    See [Correctly allocating multi-dimensional arrays](https://stackoverflow.com/questions/42094465/correctly-allocating-multi-dimensional-arrays) which explains the difference between pointer-to-pointer and 2D arrays. – Lundin Oct 20 '20 at 13:38
  • `ptr + 1` yields the address of the next `char **` object, which on x86 will be 8 bytes offset. `arr + 1` is equivalent to `&arr[1]`, which is the address of the second 10-element array of `char`, and is 10 bytes (`0xa`) offset. – John Bode Oct 20 '20 at 13:38
  • 1
    A declaration of `double *ptr` is a "double pointer". A declaration of `char **ptr` is a "pointer to pointer". – William Pursell Oct 20 '20 at 14:11
  • `char **` and `char [2][10]` are incompatible. The fact that you had to use a cast was a strong hint. If they were compatible, a cast would generally not be needed. – Tom Karzes Oct 20 '20 at 15:14

0 Answers0