【发布时间】:2017-06-08 21:20:43
【问题描述】:
我正在尝试使用在运行时创建的数组填充结构成员并收到以下错误:
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;
}
我该如何解决这个问题?
【问题讨论】:
-
您必须使用
malloc()为每个Entry分别分配内存。您必须假设调用者已经在Collection *result中分配了足够的内存。 -
像this一样使用
memcpy -
您必须为标题显式分配内存。就像 BLUEPIXY 说的那样使用 malloc
-
如前所述,
collection是一个局部变量,当您将其地址分配给*result时,它的生命周期即将结束。因此,该函数会将一个悬空指针存储到其 out 参数中,与初始化collection的问题无关。 -
作为函数参数传递的变量不能被该函数更改。
标签: c arrays memory-management struct