c - 多维数组的typedef?

标签 c multidimensional-array typedef

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/

相关文章:

mysql - 将 C header 转换为 D 时出现问题

c++ - lock_guard 是 RAII 实现还是用于实现 RAII?

c - 结构指针的这种使用正确吗?

c - 如何实现在一个文件中查找单词然后写入另一个文件?

C++ - 如何在函数声明中使用模板 typedef 解决方法?

带有运算符的 std::array 的 C++11 类型别名

c - 从二维数组中找到最大值,并将最大值之前的所有值相加,然后将最大值之后的所有值相乘

c++ - 如何在 C++ 中使用多维交错数组?

php - MySQL in() 多维数组

c - 错误: derefrencing pointer to incomplete type