C99 标准允许创建灵活的数组成员,例如
typedef struct pstring {
size_t length;
char string[];
} pstring;
然后使用类似pstring* s = malloc(sizeof(pstring) + len)
的方式进行初始化。 len
是否允许为零?它看起来是一致的,并且会不时地节省空间(当然可能不适用于 pstring
示例)。另一方面,我不知道以下代码会做什么:
pstring* s = malloc(sizeof(pstring));
s->string;
这似乎也可能适用于一个编译器而不适用于另一个编译器,或者适用于一个操作系统而不适用于另一个操作系统,或者适用于某一天而不适用于另一天,所以我真正想知道的是 标准 对此有说明。示例代码中的 malloc
是未定义的行为,还是只是对无效的 s->string
的访问,还是完全是其他东西?
最佳答案
您所做的是有效的,但访问 s->string[0] 或将 s->string 提供给任何访问数据的函数都是无效的。
C99 标准实际上说 (§6.7.2.1):
struct s { int n; double d[]; };
...
struct s t1 = { 0 }; // valid
...
The assignment to
t1.d[0]
is probably undefined behavior, but it is possible that
sizeof (struct s) >= offsetof(struct s, d) + sizeof (double)
in which case the assignment would be legitimate. Nevertheless, it cannot appear in strictly conforming code.
关于c - 创建大小为零的灵活数组成员是否合法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5037745/