在C中无效使用灵活数组ERROR

时间:2014-04-01 17:45:15

标签: c arrays struct

我有以下结构:

typedef struct dish_t {
  const char *name;
  const char *cook;
  int maxIngredients;  
  bool tasted;
  Ingredient *ingredients[];
}* Dish;

以下初始化函数:

Dish dishCreate(const char* name, const char* cook, int maxIngredients) {

if (name == NULL || cook == NULL || maxIngredients <= 0 )
{
    return NULL;
}

Dish newDish=malloc(sizeof(*newDish));

newDish->name=malloc(strlen(name)+1);
newDish->name=name;
newDish->cook=malloc(strlen(cook)+1);
newDish->cook=cook;
newDish->maxIngredients=maxIngredients;

newDish->ingredients=malloc(maxIngredients*sizeof(Ingredient*));

newDish->tasted=false;
return newDish; 
}

成分也是一种结构。 并在这一行

    newDish->ingredients=malloc(maxIngredients*sizeof(Ingredient*));

我收到错误。 我试图初始化一个指向结构的指针数组......我做错了什么?

感谢。

2 个答案:

答案 0 :(得分:2)

struct member ingredients是一个指针数组,而不是指针。您无法在C中分配数组;不改变其内容,当然也不改变其地址。模式<array> = malloc(...)在C中没有任何意义。

只需将声明更改为

即可
Ingredient *ingredients;

忘记灵活的会员;这是一种内存分配策略,不会增加程序的语义或质量。

在某些类型的程序中,结构末端的灵活数组可能很有用 优化,因为它们减少了对分配器的调用次数:标头结构加上一些可变数据可以在单个malloc调用中分配,并在单个free调用中释放。

这并没有在程序中实现任何语义上的任何兴趣,并且天真地使用这种方法会使程序变慢并浪费内存,因为最后两个或多个具有灵活数据的对象必须拥有自己的副本在使用指针的程序可以有效地共享该数据的情况下的数据。

答案 1 :(得分:0)

问题是你尝试制作一个灵活的指针数组,然后你尝试使用malloc来创建它,这不是你应该做的。

对于结构中的灵活数组,您应该将结构的初始分配更长,以适应数组中元素的数量。

如果您要对数组使用malloc,那么您也可以使用普通指针。


解释我的意思:

typedef struct dish_t {
    ...
    Ingredient ingredients[];
}* Dish;

...

Dish myDish = malloc(sizeof(*myDish) + sizeof(Ingredient) * 10);

以上malloc为数组中的十个条目分配结构和足够的空间。

相关问题