[英]Compiler error: incompatible types when assigning to 'struct' from type 'void *' during malloc
EDIT -- can the down voter explain? 编辑 - 下选民可以解释一下吗? I have a clear question, with supporting evidence, and proof of prior investigation.
我有一个明确的问题,有证据支持,以及事先调查的证据。 I would like to understand why you are down voting me...?
我想明白你为什么要投票给我......?
I am getting this error when I compile with gcc: 我用gcc编译时收到此错误:
error: incompatible types when assigning to type 'struct cell' from type 'void *
The problem lines are: 问题是:
struct cell* cells = NULL;
cells = malloc(sizeof(struct cell) * length);
for (i = 0; i < length; i++) {
cells[i] = malloc(sizeof(struct cell) * width);
I believe I have followed the proper protocol, as described here and also here . 我相信我已经遵循正确的协议,如所描述这里也这里 。 What am I missing?
我错过了什么?
For a multidimensional array, you want an array of type struct cell** cells
: 对于多维数组,您需要一个
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);
}
Now cells
is a multidimensional array, where the first index range is the length and the second index range is the width. 现在,
cells
是一个多维数组,其中第一个索引范围是长度,第二个索引范围是宽度。
malloc()
always returns a pointer of type void *
you need to type cast malloc()
总是返回一个void *
类型的指针,你需要输入cast
To allocate memory for single element: 为单个元素分配内存:
struct cell* new = (struct cell*) malloc(sizeof(struct cell)); //This will allocate memory and new is pointer
To access data members : 要访问数据成员:
new->member_name = value; //dot(.) operator doesn't work as new is a pointer and not an identifier
To allocate memory for array : 为数组分配内存:
struct cell* base = (struct cell*) malloc(sizeof(struct cell) * length); //This will allocate memory and base is base of array
To access data members : 要访问数据成员:
base[i].member_name = value; //When accessing elements of array the -> operator doesn't work.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.