编译器错误:在malloc期间从类型'void *'分配给'struct'时出现不兼容的类型

时间:2013-02-20 15:59:51

标签: c multidimensional-array malloc

编辑 - 下选民可以解释一下吗?我有一个明确的问题,有证据支持,以及事先调查的证据。我想了解你为什么要投票给我......?


使用gcc编译时出现此错误:

error: incompatible types when assigning to type ‘struct cell’ from type ‘void *

问题在于:

    struct cell* cells = NULL;
    cells = malloc(sizeof(struct cell) * length);
    for (i = 0; i < length; i++) {
            cells[i] = malloc(sizeof(struct cell) * width);

我相信我已遵循正确的协议,如herehere所述。我错过了什么?

2 个答案:

答案 0 :(得分:6)

对于多维数组,您需要一个类型为struct cell** cells的数组:

struct cell** cells = NULL;
cells = malloc(sizeof(struct cell*) * length);
for(int i = 0; i < length; i++) {
  cells[i] = malloc(sizeof(struct cell)*width);
}

现在cells是一个多维数组,其中第一个索引范围是长度,第二个索引范围是宽度。

答案 1 :(得分:0)

malloc()始终返回类型为void *的指针,您需要键入强制类型转换

为单个元素分配内存:

struct cell* new = (struct cell*) malloc(sizeof(struct cell)); //This will allocate memory and new is pointer

访问数据成员:

new->member_name = value; //dot(.) operator doesn't work as new is a pointer and not an identifier

为数组分配内存:

struct cell* base = (struct cell*) malloc(sizeof(struct cell) * length); //This will allocate memory and base is base of array

访问数据成员:

base[i].member_name = value; //When accessing elements of array the -> operator doesn't work.