【发布时间】:2012-01-08 22:40:21
【问题描述】:
typedef int array [x][];
这是什么意思。如果我们有这样的 typedef 会发生什么。这是我的面试问题。
【问题讨论】:
标签: c multidimensional-array typedef
typedef int array [x][];
这是什么意思。如果我们有这样的 typedef 会发生什么。这是我的面试问题。
【问题讨论】:
标签: c multidimensional-array 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
【讨论】:
你会得到一个编译错误。对于多维数组,最多可以省略第一维。因此,例如,int array[][x] 将是有效的。
【讨论】:
您将获得诊断。
int [x][] 是不完整的数组类型,无法完成。
【讨论】: