Search code examples
cstructvoid-pointers

How to initialize an void* pointer from struct


I have a struct Element. When I try to initialize the elements array to NULL, I get the error: incompatible types when assigning to type Element from type void *.

How to initialize the void * array?

typedef struct _Element Element;
struct _Element {
    void* data;
};

typedef struct _ArrayList ArrayList;
struct _ArrayList {
    int size;
    Element *elements;
};

int main() {
    ArrayList *list;
    list->size = 100;
    list->elements = (Element*)calloc(sizeof(Element), list->size);

    for (i = 0; i < list->size; i++) {
        /*
         * error: incompatible types when assigning to type 
         * ‘Element’ from type ‘void *’
         */
        list->elements[i] = NULL;
    }
}

Solution

  • Firstly, you never allocated memory for your list object! Your list pointer is uninitialized and points nowhere. Trying to apply the -> operator to it causes undefined behavior.

    I don't know what your final intent is, but it should be either something like

    ArrayList *list = malloc(sizeof *list);
    list->size = 100;
    ...
    

    or

    ArrayList list;
    list.size = 100;
    ...
    

    Secondly, your void * pointer is actually a named field called data inside Element struct

    for(i = 0; i < list->size; i++)
        list->elements[i].data = NULL; 
    

    Thirdly, becuse you used calloc the memory is already sort of "initialized" with all-zero bit-pattern (including your data fileds). Formally, such bit-pattern in void * is not guaranteed to represent a null pointer, but on most platforms it actually does.

    P.S. Don't cast the result of calloc

     list->elements = calloc(sizeof(Element), list->size);
    

    or event better

     list->elements = calloc(sizeof *list->elements, list->size);