多维数组的typedef?

Del*_*lhi 5 c typedef multidimensional-array

typedef int array [x][];
Run Code Online (Sandbox Code Playgroud)

这意味着什么.如果我们有这样的typedef会发生什么.这是我的面试问题.

Tim*_*nes 8

我们假设你有一个地方:

#define x 3
Run Code Online (Sandbox Code Playgroud)

正如其他人指出的那样,typedef int array [3][];不会编译.您只能省略数组长度的最重要(即第一个)元素.

但你可以说:

typedef int array [][3];
Run Code Online (Sandbox Code Playgroud)

这意味着它array是一个长度为3的数组的int数组(尚未指定的长度).

要使用它,您需要指定长度.您可以使用如下的初始化程序执行此操作:

array A = {{1,2,3,},{4,5,6}};   // A now has the dimensions [2][3]
Run Code Online (Sandbox Code Playgroud)

但你不能说:

array A; 
Run Code Online (Sandbox Code Playgroud)

在这种情况下,A未指定第一个维度,因此编译器不知道要为其分配多少空间.

请注意,array在函数定义中使用此类型也很好- 因为函数定义中的数组总是被编译器转换为指向其第一个元素的指针:

// these are all the same
void foo(array A);
void foo(int A[][3]);
void foo(int (*A)[3]); // this is the one the compiler will see
Run Code Online (Sandbox Code Playgroud)

请注意,在这种情况下:

void foo(int A[10][3]); 
Run Code Online (Sandbox Code Playgroud)

编译器仍然看到

void foo(int (*A)[3]);
Run Code Online (Sandbox Code Playgroud)

所以,10部分A[10][3]被忽略了.

综上所述:

typedef int array [3][]; // incomplete type, won't compile
typedef int array [][3]; // int array (of as-yet unspecified length) 
                         // of length 3 arrays
Run Code Online (Sandbox Code Playgroud)


oua*_*uah 1

您会得到诊断结果。

int [x][]是无法完成的不完整数组类型。