Doesn't a 2D array decay to pointer to pointer

后端 未结 3 1908
终归单人心
终归单人心 2020-11-30 14:52

Up till now I was pretty much sure that

int arr[4][5];

Then arr will decay to pointer to pointer.

But this link prov

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 15:07

    In general, a 2-dim array is implemented as an array of pointers (which, in a sense, is a pointer to a pointer... a pointer to the first element (i.e., pointer) in the array) When you specify the first index (i.e., arr[x]), it indexes into the array of pointers and gives the pointer to the x-th row. The the second index (i.e., arr[x][y]) gives the y-th int in that row.

    In the case of a static declared array (as in your example), the actual storage is allocated as a single block ... in your example, as a single contiguous block of 20 integers (80 bytes, on most platforms). In this case, there IS no array of pointers, the compiler just does the appropriate arithmetic to address the correct element of the array. Specifically, arr[x][y] is equivalent to *(arr + x * 5 + y). This automatically-adjusted-arithmetic only happens in the original scope of the array... if you pass the array to a function, the dimension information is lost (just as the dimension is lost for a 1-dim array), and you have to do the array-indexing calculations explicitly.

    To avoid this, do NOT declare the array as static, but as an array of pointers, with each pointer pointed to a 1-dim array, such as in this example:

    int arr0[5];
    int arr1[5];
    int arr2[5];
    int arr3[5];
    int* arr[4] = { arr0, arr1, arr2, arr3 };
    

    Then, when you pass arr to a function, you can address it as a 2-dim array within the function as well.

提交回复
热议问题