Are C multidimensional arrays contiguous without holes?

六眼飞鱼酱① 提交于 2021-02-20 05:59:51

问题


I am unable to find in the C standard docs specifically where it says that multidimensional arrays are contiguous. While it can be inferred from the fact that array elements are contiguous, I want some perspective from the community.

The following code prints out the numbers in the order that I would expect, which is 1 - 9.

#include <stdio.h>

int main()
{
    int a[][3] = {{1,2,3},{4,5,6},{7,8,9}};
    int* p = (int*)a;
    int i;

    for (i = 0; i < sizeof(a)/sizeof(int); i++)
        printf("%d ",p[i]);

    return 0;
}

回答1:


Yes, it can be obtained by induction. (Just to add, as a suggestion, if that helps, try to think of multi-dimensional arrays as array of arrays.)

For example, consider an array like a[3][3].

  • So, a[0][0], a[0][1] and a[0][2] are elements of a[0] and they will be contiguous.

  • Next, a[0] and a[1] are elements of a, so it will be contiguous

an so on.

Taken together, a[0][2] and a[1][0] will be residing next to each other, thereby continuing the contiguity.

For better visual representation, see the below illustration.

The array, say int arr[4][5], has four rows, a[0],a[1], a[2] and a[3] and they are contiguous.

Now each of those rows have five columns, like a[n][0], a[n][1], a[n][2], a[n][3], a[n][4] and they are contiguous.

So, the all the elements (and elements of elements) of the array are contiguous.




回答2:


According to 6.2.5 Types p20:

An array type describes a contiguously allocated nonempty set of objects with a particular member object type, called the element type. The element type shall be complete whenever the array type is specified. ...

Therefore all array types, multidimensional or not, are contiguously allocated.




回答3:


Yes they are contiguous. I would say the fact "an array" (i.e. singular) is contiguous infers that a multi-dimensional one is. Each array within it must be contiguous and the outer array must be a contiguous collection of those arrays...




回答4:


C does not explicitly have multi-dimentional arrays, C have array of arrays, and arrays in C are contiguously represented in memory. Hence all arrays in C are contiguous.



来源:https://stackoverflow.com/questions/36647286/are-c-multidimensional-arrays-contiguous-without-holes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!