Reputation: 119
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;
}
}
Upvotes: 1
Views: 5038
Reputation: 46323
Apart from all the logical errors, the compiler error is the result of trying to assign a value (NULL) to a struct-typed variable. The fact that the struct contains a void *
is coincidental. You'd get the same error with:
typedef struct _Element Element;
struct _Element{
int data;
};
Element e;
e = NULL;
This is most likely a mistake from what you intended to do, which is assign a value to the variable inside the struct:
for(i = 0; i < list->size; i++)
list->elements[i].data = NULL;
Upvotes: 0
Reputation: 320381
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);
Upvotes: 2