C 中的多维数组是连续的。以下:
int a[4][5];
由 4 个 int[5] 组成,在内存中彼此相邻。
指针数组:
int *a[4];
是锯齿状的。每个指针都可以指向不同长度的单独数组(的第一个元素)。
a[i][j] 等价于 ((a+i)+j)。请参阅 C11 标准,第 6.5.2.1 节:
The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2)))
因此,a[i][j]等价于(*(a+i))[j],等价于((a+i)+j)。
之所以存在这种等价性,是因为在大多数情况下,数组类型的表达式会衰减为指向其第一个元素的指针(C11 标准,6.3.2.1)。 a[i][j] 解释如下:
a is an array of arrays, so it decays to a pointer to a[0], the first subarray.
a+i is a pointer to the ith subarray of a.
a[i] is equivalent to *(a+i), dereferencing a pointer to the ith subarray of a. Since this is an expression of array type, it decays to a pointer to a[i][0].
a[i][j] is equivalent to *(*(a+i)+j), dereferencing a pointer to the jth element of the ith subarray of a.
请注意,指向数组的指针不同于指向其第一个元素的指针。 a+i 是指向数组的指针;它不是数组类型的表达式,并且无论是指向指针的指针还是指向任何其他类型的指针,它都不会衰减。
and for some reason printing *a in single dimensional array will print the first element of the array whereas *a in a multidimensional array will print a random number. Why is this so?
对于二维数组,您需要相应地取消引用它,
printf("\nvalue : %d",**a);
打印数组的第一个元素。