Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the type of 2d array's element in c and c++?

e.g.

int arr[2][3] = ...

The type of arr[0] is

int (*)[3] // pointer to int[3], which is a pointer. 

Or

int[3] // an array whose size is 3, which is an array. 

Google tells me nothing about the question.

I know pointer and array are different types(derived types).

Maybe C and C++ treat it differently, I hope to see standard wording.

like image 985
Chen Li Avatar asked Dec 05 '22 12:12

Chen Li


1 Answers

arr[0] is of type int [3] which is not a pointer.

int (*p)[3] is of type int(*)[3] meaning pointer to an array of 3 elements.

Pointer is not array and array is not pointer.

Now when you pass this 2d array to a function (or any case where decaying occurs) then it decays into pointer to the first element which is int (*)[3].

To be more clear in C 2d array is nothing but array of arrays.

Dissecting

  • arr is an array each of element of which is again an array with 3 elements.

  • arr[0] in most of the cases (except sizeof etc) will decay into pointer to first element it contains which is an int*.

  • arr[0][0] is an int.

  • At last &arr[0] .. guess what? This is of type int(*)[3].

like image 126
user2736738 Avatar answered Dec 14 '22 23:12

user2736738