面试题答案
一键面试-
首先,对于三维数组
int threeD[2][3][4];
,它在内存中是按行优先顺序存储的。 -
指针
int *ptr = &threeD[0][0][0];
指向数组的首元素。 -
要访问
threeD[1][2][3]
,计算过程如下:- 先计算
threeD[1]
相对threeD[0]
的偏移。由于threeD
是三维数组,threeD[1]
相对于threeD[0]
的偏移量是1 * 3 * 4
个int
类型的大小。这是因为每一个threeD[i]
实际上是一个int [3][4]
类型的数组,每个这样的二维数组有3 * 4
个int
元素。 - 接着计算
threeD[1][2]
相对threeD[1][0]
的偏移。threeD[1][2]
相对于threeD[1][0]
的偏移量是2 * 4
个int
类型的大小,因为threeD[1][j]
是int [4]
类型的数组,每个这样的一维数组有4
个int
元素。 - 最后计算
threeD[1][2][3]
相对threeD[1][2][0]
的偏移,偏移量是3
个int
类型的大小。
- 先计算
-
综合起来,
threeD[1][2][3]
相对于threeD[0][0][0]
的偏移量是1 * 3 * 4 + 2 * 4 + 3
个int
类型的大小。 -
通过指针
ptr
访问threeD[1][2][3]
的代码如下:
#include <stdio.h>
int main() {
int threeD[2][3][4];
int *ptr = &threeD[0][0][0];
int target = *(ptr + 1 * 3 * 4 + 2 * 4 + 3);
printf("The value of threeD[1][2][3] is: %d\n", target);
return 0;
}
- 在上述代码中,
ptr + 1 * 3 * 4 + 2 * 4 + 3
计算出了threeD[1][2][3]
相对于ptr
(即threeD[0][0][0]
)的偏移位置,然后通过*
解引用操作符获取该位置的值。
C语言多维数组名的特性:
- 多维数组名可以看作是指向第一个元素的指针。例如
threeD
可以看作是指向threeD[0]
的指针,threeD[0]
又可以看作是指向threeD[0][0]
的指针,threeD[0][0]
是一个int
类型的元素。 - 数组在内存中按行优先顺序存储,这使得我们可以通过简单的乘法和加法运算来计算出目标元素相对于首元素的偏移量,从而通过指针正确定位到目标元素。
通过上述指针运算,我们能够准确地访问到 threeD[1][2][3]
元素。