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

12,489

For a multidimensional array, you want 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);
}

Now cells is a multidimensional array, where the first index range is the length and the second index range is the width.

Share:
12,489
d0rmLife
Author by

d0rmLife

Updated on June 05, 2022

Comments

  • d0rmLife
    d0rmLife about 2 years

    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:

    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?

  • d0rmLife
    d0rmLife over 11 years
    Great, the compiler is happy :) Makes sense, thanks for explaining.
  • Keith Thompson
    Keith Thompson over 11 years
    Strictly speaking, a multidimensional array is simply an array of arrays. You can create a data structure that acts like a multidimensional array (with more flexibility and more need to manage your own memory) using an array of pointers.
  • d0rmLife
    d0rmLife over 11 years
    @KeithThompson Is the alternate data structure you are referring to an array that would result from a command something like: struct cell* cells = malloc(sizeof(struct cell) * length * width); ?
  • John Colanduoni
    John Colanduoni over 11 years
    @d0rmLife What my code above gives you is an array of pointers to arrays. struct cell* cells = malloc(sizeof(struct cell) * length * width) gives you a one dimensional array, but it can be indexed using something along the lines of cells[i*width+j].
  • Keith Thompson
    Keith Thompson over 11 years
    @d0rmLife: Partly. To emulate a 2D array like that, you need to allocate memory both for an array of pointers (each element of which points to a row of the 2D array), and for each row. Basically what you're doing in the code in your question, apart from the type error.