typedef int array [x][];
这是什么意思。如果我们有这样的 typedef 会发生什么。这是我的面试问题。
最佳答案
假设您有某个地方:
#define x 3
正如其他人指出的那样,typedef int array [3][];
将无法编译。您只能省略数组长度中最重要的(即第一个)元素。
但是你可以说:
typedef int array [][3];
这意味着 array
是一个长度为 3 的 int 数组(长度尚未指定)。
要使用它,您需要指定长度。您可以使用像这样的初始化程序来做到这一点:
array A = {{1,2,3,},{4,5,6}}; // A now has the dimensions [2][3]
但是你不能说:
array A;
在这种情况下,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
请注意,在这种情况下:
void foo(int A[10][3]);
编译器仍然能看到
void foo(int (*A)[3]);
因此,A[10][3]
的 10
部分将被忽略。
总结:
typedef int array [3][]; // incomplete type, won't compile
typedef int array [][3]; // int array (of as-yet unspecified length)
// of length 3 arrays
关于c - 多维数组的typedef?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8782023/