5

编辑——否决的选民可以解释吗?我有一个明确的问题,有支持性证据和先前调查的证据。我想了解你为什么不给我投票……?


使用 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);

我相信我已经遵循了正确的协议,如此处和此处所描述。我错过了什么?

4

2 回答 2

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是一个多维数组,其中第一个索引范围是长度,第二个索引范围是宽度。

于 2013-02-20T16:03:46.173 回答
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.

于 2019-06-01T15:21:14.377 回答