简体   繁体   English

我怎样才能正确地将 void* 转换为 int?

[英]how can i cast void* to int correctly?

When I'm studying C, I find this program:我在学习 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;
}

When compiling, output "warning: assignment to void* from int makes pointer from integer without a cast" How can I solve this problem?编译时,output“警告:从 int 分配给 void* 使指针来自 integer 没有强制转换”我该如何解决这个问题?

This will solve it.这将解决它。 data is a pointer, so you need to assign it to the address of the variable: data是一个指针,因此您需要将其分配给变量的地址:

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除此之外,不要投 malloc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM