Compiler error: incompatible types when assigning "struct" from type "void *" during malloc

EDIT - Does the lower voter explain? I have a clear question with supporting evidence and evidence of a preliminary investigation. I would like to understand why you vote me ...?


I get this error when compiling with gcc:

error: incompatible types when assigning to type โ€˜struct cellโ€™ from type โ€˜void *

Problem lines:

    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 that I have followed the proper protocol as described here as well as here . What am I missing?

+5
source share
1 answer

For a multidimensional array, you need an array of type 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 - , - , - .

+6

All Articles