gpt4 book ai didi

c - 灵活数组成员的非静态初始化

转载 作者:行者123 更新时间:2023-11-30 14:56:45 25 4
gpt4 key购买 nike

我尝试使用运行时创建的数组填充结构成员并收到以下错误:

error: non-static initialization of a flexible array member
.entries = entries
^

我已经隔离了问题并用更简单的代码重现了它以使其更清晰:

#include <stdlib.h>

typedef struct entry {
char *title;
int id;
} Entry;

typedef struct collection {
size_t size;
Entry entries[];
} Collection;

// This function signature may not be changed
void populate(int n, Collection *result){

Entry entries[n];

for (int i = 0; i < n; ++i) {
Entry entry = {
.title = "Title",
.id = i
};

entries[i] = entry;
}

Collection collection = {
.size = n,
.entries = entries
};

result = &collection;
}

我该如何解决这个问题?

最佳答案

实际上,用灵活的数组成员初始化结构体并不简单;您必须为稍后要复制的条目分配足够空间的集合项目。所以你可以写如下内容:

Collection *coll = malloc(sizeof(Collection)+n*sizeof(Entry));
coll->size = n;
memcpy (coll->entries, entries, n*sizeof(Entry));

除了使用这样的“手写”,我没有其他办法malloc .

但请注意,如果内存分配预计在函数populate中完成,函数签名populate不能保持原样,因为它不允许“返回”或设置指向新分配的 Collection 的指针-目的。在这种情况下,签名必须更改为 void populate(int n, Collection **result)或进入Collection *populate(int n) .

关于c - 灵活数组成员的非静态初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44445759/

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