[英]non-static initialization of a flexible array member
我试图用在运行时创建的数组填充struct成员,并得到以下错误:
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
-object。 在这种情况下,必须将签名更改为void populate(int n, Collection **result)
或更改为Collection *populate(int n)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.