【发布时间】:2014-06-06 12:58:15
【问题描述】:
我在结构末尾的驱动程序中看到了这个语句的用法。 谁能解释一下这个语句的用途是什么?它在内部是如何工作的? 我的意思是编译器会将其视为数组还是变量?
【问题讨论】:
-
我猜它是为了 struct hack。 read this
-
那是struct hack。现在你会改用Flexible Array Members。
我在结构末尾的驱动程序中看到了这个语句的用法。 谁能解释一下这个语句的用途是什么?它在内部是如何工作的? 我的意思是编译器会将其视为数组还是变量?
【问题讨论】:
在 C 中,通过为固定大小的字段和数组中所需的任何内容分配足够的内存,允许您将可变大小的数组放在结构的末尾是一个技巧。例如:
struct array {
size_t size;
int a[]; // strictly, it should be incomplete rather than zero sized
};
struct array * make_array(size_t size) {
struct array * array = malloc(sizeof (struct array) + size * sizeof (int));
array->size = size;
return array;
}
struct array * array = make_array(2);
array->a[1] = 42; // No problem: there's enough memory for two array elements
在 C++ 中,它是无效的。请改用std::vector。
【讨论】:
虽然这两个标准都不支持大小为 0 的数组,但许多编译器允许它们作为扩展。标准化的 C 方式 (C99+) 完全忽略了大小。
Thiis 用于描述由起始字段和可变数量的数组元素组成的数据结构,以及方便地访问它们。
【讨论】: