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]
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.
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With