gpt4 book ai didi

c - 我们如何创建一个结构数组,它的最后一个字段是灵活数组?

转载 作者:太空狗 更新时间:2023-10-29 15:25:26 26 4
gpt4 key购买 nike

假设我们有:

struct A {
int i;
char c[1];
};

通常我会使用 malloc() 来创建 A 的实例,例如:

#define LEN 10

struct A *my_A = malloc(sizeof(A) + LEN * sizeof(char));

但是如果我尝试创建一个 A 数组,这将不起作用

最佳答案

具有灵活数组成员的 struct 不能是数组的成员。这在 C standard 的第 6.7.2.1p3 节中有明确说明。 :

A structure or union shall not contain a member with incomplete or function type (hence, a structure shall not contain an instance of itself, but may contain a pointer to an instance of itself), except that the last member of a structure with more than one named member may have incomplete array type; such a structure (and any union containing, possibly recursively, a member that is such a structure) shall not be a member of a structure or an element of an array.

您需要做的是用指针而不是灵活的数组成员声明结构,并为每个实例分配空间。

例如:

struct A {
int i;
char *c;
};

struct A arr[100];

for (int i=0; i<100; i++) {
arr[i].c = malloc(LEN);
}

关于c - 我们如何创建一个结构数组,它的最后一个字段是灵活数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54524735/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com