如果我有一个只有一个元素的数组,我们可以说它与指针相同。 但是大小为零的数组在内存中表示为什么?
当我声明一个变量int * table [0]
时会发生什么?
零长度数组在C标准中并没有得到技术上的支持。然而,像gcc这样的一些编译器允许它们作为扩展使用。
它们是一种创建灵活的数组成员的早期C99方式,如下所示:
typedef struct {
int len;
int contents[0];
} arr;
然后,您可以在结尾为数组初始化所需的任意空间:
arr* a = malloc(sizeof(*a) + sizeof(a->contents) * 10); /* for a length-10 array */
a->len = 10;
int contents[];
将是一个灵活的数组成员(FAM)。而 int contents[0];
则不是 FAM。 - chux - Reinstate MonicaDeclaring zero-length arrays is allowed in GNU C as an extension. A zero-length array can be useful as the last element of a structure that is really a header for a variable-length object:
struct line { int length; char contents[0]; }; struct line *thisline = (struct line *) malloc (sizeof (struct line) + this_length); thisline->length = this_length;
Although the size of a zero-length array is zero, an array member of this kind may increase the size of the enclosing type as a result of tail padding. The offset of a zero-length array member from the beginning of the enclosing structure is the same as the offset of an array with one or more elements of the same type. The alignment of a zero-length array is the same as the alignment of its elements.