Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: incompatible types when assigning to type 'values' from type 'void *'?

Tags:

c

I get this error when I'm trying to malloc some memory for my struct of ints.

typedef struct _values {
random ints;
} values;

I have tried the lines below but my compiler doesn't like it. How do I fix the error?

values v;
v = malloc(sizeof(values));
like image 974
Sam Avatar asked Jun 08 '26 00:06

Sam


1 Answers

You forgot to add the asterisk (*) after the values and before the v to mark it as a pointer: values *v;

The way you set it now, the v (without the asterisk) is defined as a stack variable and would be allocated on the stack and discarded once the function ends. It's type will be simply values. malloc is used to allocate memory on the heap and returns a pointer to the memory. Sine the function has no way of knowing the type it returns it as a void * type - Which gives you your error - you're attempting to assign a void * type into a struct type, which the compiler can't do, nor can the compiler find a legitimate cast that could resolve the problem.

like image 73
immortal Avatar answered Jun 10 '26 19:06

immortal