0

I have a doubt about multi-dimensional arrays and pointers notation, as below.

int arr[2][4] = {{1,2,3,4}, {5,6,7,8}};
printf("%d\n", (arr+1));
printf("%d\n", *(arr+1));

Why in both printf() calls, the result printed is the same? Both bring the addresses of the second array inside of the arr. The first one I understand because arr is a memory address and so, adding 1 to it moves the pointer ahead by (the size of the inner array * size of integer). But for the second one I am confused because if I put * before (arr+1), shoudn't it be the value on the address of (arr+1)?

vmpyr
  • 95
  • 4
  • 3
    FYI: printing an address with `"%d"` invokes UB. – pmg Jun 23 '23 at 16:27
  • 2
    The code presented is not valid C. Putting a data type, maybe `int`, in front of `arr[2][4]` would fix the worst problem by making that into a declaration. – John Bollinger Jun 23 '23 at 16:27
  • With additional useful related info in [How come an array's address is equal to its value in C?](https://stackoverflow.com/q/2528318/364696) and [What is array to pointer decay?](https://stackoverflow.com/q/1461432/364696). – ShadowRanger Jun 23 '23 at 16:48
  • @Filipe Andrade, "result printed in the screen is the same" --> technically the 2 pointers do not need to be the _same_ bit pattern, just _equivalent_ pointers - once converted to `void *`. – chux - Reinstate Monica Jun 23 '23 at 17:07

3 Answers3

1

Values are the same, but types are different: int(*)[4] (pointer to array of 4 ints) vs int * (pointer to int, but before the implicit conversion caused by passing it to a function it was int[4], an array of 4 ints).

Those two values are &arr[1] and &arr[1][0] respectively. The first subarray and its first element have the same address.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
0

arr + 1 is the address of a block of 4 items.
*(arr + 1) is the address of 1 item.

pmg
  • 106,608
  • 13
  • 126
  • 198
0

(arr) points to the first memory address of the 2 * 4 array, i.e., arr[0][0].
(arr+1) points to the 2nd 1-D array comprising arr, i.e., it points to the array arr[1].

Now, *(arr+1) is basically the address of the first element of the 2nd 1-D array comprising arr, i.e., it points to the element arr[1][0].

If you know pointers well, arr[1] is the same address as arr[1][0].

You can confirm that by checking **(arr+1), which will output 5 in your case.

vmpyr
  • 95
  • 4