-2

When I'm studying C, I find this program:

#include<stdio.h>
struct Base
{
void* data;
}
int main()
{
struct Base* base = (struct Base*)malloc(sizeof(struct Base));
if(!base) return -1;
int value = 90;
base->data = value;
printf("%d", base->data);
return 0;
}

When compiling, output "warning: assignment to void* from int makes pointer from integer without a cast" How can I solve this problem?

Coffee
  • 1

1 Answers1

2

This will solve it. data is a pointer, so you need to assign it to the address of the variable:

base->data = &value;
printf("%d", *(int*)base->data);

If you really mean what you're writing, but just want to get rid of the warning, use this:

base->data = (void*)value;

But if you're doing that, it's a good sign you're doing something wrong.

Other than that, Don't cast malloc

klutt
  • 30,332
  • 17
  • 55
  • 95
  • I suppose it's possible, though unlikely, OP is using the address of `data` as the `int` value. `base->data = (void *)value`; `value = (int)(base->data)`. – Fiddling Bits Mar 24 '21 at 14:30