struct test{
unsigned long int asd[][3][6];
};
sizeof(struct test)
返回 0。因此,如果这是
struct test{
unsigned long int asd[0][3][6];
};
这样的字段声明有实际用途吗?您可能还会考虑模板元编程的东西,这总是令人惊讶。
最佳答案
第一个示例演示了灵活数组成员 的使用,这是 C99 的一个特性。然而,为了让该片段能够编译,您需要在您的 struct
中有另一个成员,即:
struct test{
int a;
unsigned long int asd[][3][6];
};
This documentation在 gcc 上告诉你为什么 sizeof
求值为零,以及普通数组的语法差异:
In ISO C90, you would have to give contents a length of 1, which means either you waste space or complicate the argument to malloc.
In ISO C99, you would use a flexible array member, which is slightly different in syntax and semantics:
- Flexible array members are written as contents[] without the 0.
- Flexible array members have incomplete type, and so the sizeof operator may not be applied. As a quirk of the original implementation of zero-length arrays, sizeof evaluates to zero.
- Flexible array members may only appear as the last member of a struct that is otherwise non-empty.
- A structure containing a flexible array member, or a union containing such a structure (possibly recursively), may not be a member of a structure or an element of an array. (However, these uses are permitted by GCC as extensions.)
关于c - 无维数组字段,它的用途?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8705860/