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

标签 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*));

我得到了错误。 我正在尝试初始化指向结构的指针数组...我做错了什么?

谢谢。

最佳答案

结构成员 ingredients是指针数组,不是指针。您不能在 C 中分配给数组;不要更改其内容,当然也不要更改其地址。花纹<array> = malloc(...)在 C 中没有意义。

只需将声明更改为

Ingredient *ingredients;

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

在某些类型的程序中,结构末尾的灵活数组可能很有用 优化,因为它们减少了对分配器的调用次数:可以在单个 malloc 中分配 header 结构和一些可变数据。调用并在单个 free 中发布称呼。

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

关于c - 在 C 中无效使用灵活数组 ERROR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22793111/

相关文章:

c - 从 GSL 库中获取 C gsl_fit_linear() 函数中线性回归的 p 值

c++ - Windows DLL 用文件初始化常量 c 字符串数组

c++ - 优化:为什么 < 比 multiple 更昂贵!=

php - 将 PHP 对象转换为关联数组

c - 如何在C中交换两个结构

c - 输出从函数返回结构体

c - 指向结构数组编译错误的双指针

javascript - 如何验证数组(矩阵)格式?

c - 使用宏初始化结构

c - 通过结构别名数组