C 如何正确地将void*转换为int?

C 如何正确地将void*转换为int?,c,pointers,casting,C,Pointers,Casting,当我学习C时,我发现这个程序: #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

当我学习C时,我发现这个程序:

#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;
}
#包括
结构基
{
作废*数据;
}
int main()
{
struct Base*Base=(struct Base*)malloc(sizeof(struct Base));
如果(!base)返回-1;
int值=90;
基础->数据=值;
printf(“%d”,基础->数据);
返回0;
}
编译时,输出“警告:对void*from int的赋值使指针从整数变为无强制转换”
我怎样才能解决这个问题?

这样就可以解决了<代码>数据是指针,因此需要将其分配给变量的地址:

base->data = &value;
printf("%d", *(int*)base->data);
如果你真的想表达你所写的,但只是想摆脱警告,请使用以下方法:

base->data = (void*)value;
但如果你这么做,这是一个好迹象,表明你做错了什么


除此之外,

这不是您拥有的程序,它不会编译,因为您缺少一个分号。此外,如果您不告诉需要做什么,也无法解决问题。但在这种情况下,最明智的做法是使用
int数据而不是
void*数据
。也不要强制转换
malloc
的返回值-您缺少
#include
,因此您的程序严重损坏。复制粘贴发布问题时编译的确切代码通过执行
#include
提供malloc声明您所做的一切毫无意义。
int
不是
void*
,试图给
void*
赋值是一个等待发生的灾难。30年前,将指针视为整数是很常见的,这导致了无数的编程错误。停止延续十年的坏习惯。我想这是可能的,尽管不太可能,OP使用
data
的地址作为
int
值<代码>基础->数据=(无效*)值
<代码>值=(int)(基本->数据)。