C多维数组是连续的,没有孔吗? [英] Are C multidimensional arrays contiguous without holes?
问题描述
我无法在C标准文档中特别找到多维数组是连续的.虽然可以从
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;
}
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]
anda[0][2]
are elements ofa[0]
and they will be contiguous.Next,
a[0]
anda[1]
are elements ofa
, 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.
这篇关于C多维数组是连续的,没有孔吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!