C语言 警告:返回使指针从整数而不进行强制转换,但根据需要返回整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18117376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
warning: return makes pointer from integer without a cast but returns integer as desired
提问by user2662982
I'm trying to find out the proper way to return an integer from a void * function call within C.
我试图找出从 C 中的 void * 函数调用返回整数的正确方法。
ie ..
IE ..
#include <stdio.h>
void *myfunction() {
int x = 5;
return x;
}
int main() {
printf("%d\n", myfunction());
return 0;
}
But I keep getting:
但我不断得到:
warning: return makes pointer from integer without a cast
警告:返回使指针来自整数而不进行强制转换
Is there a cast I need to do to make this work? It seems to return x without problem, the real myfunction returns pointers to structs and character strings as well which all work as expected.
我需要做演员来完成这项工作吗?它似乎毫无问题地返回 x,真正的 myfunction 返回指向结构和字符串的指针,这些都按预期工作。
采纳答案by user2663103
It's not obvious what you're trying to accomplish here, but I'll assume you're trying to do some pointer arithmetic with x, and would like x to be an integer for this arithmetic but a void pointer on return. Without getting into why this does or doesn't make sense, you can eliminate the warning by explicitly casting x to a void pointer.
您在这里尝试完成的任务并不明显,但我假设您正在尝试对 x 进行一些指针算术运算,并且希望 x 是该算术的整数,但返回时为空指针。在不了解为什么这样做有意义或没有意义的情况下,您可以通过将 x 显式转换为空指针来消除警告。
void *myfunction() {
int x = 5;
return (void *)x;
}
This will most likely raise another warning, depending on how your system implements pointers. You may need to use a long instead of an int.
这很可能会引发另一个警告,具体取决于您的系统如何实现指针。您可能需要使用 long 而不是 int。
void *myfunction() {
long x = 5;
return (void *)x;
}
回答by aaronman
A void * is a pointer to anything, you need to return an address.
void * 是指向任何内容的指针,您需要返回一个地址。
void * myfunction() {
int * x = malloc(sizeof(int));
*x=5;
return x;
}
That being said you shouldn't need to return a void *for an int, you should return int *or even better just int
话虽如此,您不需要void *为 int返回 a ,您应该返回int *甚至更好int
回答by 1''
Although you'd think the easiest way to do this would be:
尽管您认为最简单的方法是:
void *myfunction() {
int x = 5;
return &x; // wrong
}
this is actually undefined behaviour, since x is allocated on the stack, and the stack frame is "rolled up" when the function returns. The silly but correct way is:
这实际上是未定义的行为,因为 x 分配在堆栈上,并且当函数返回时堆栈帧被“卷起”。愚蠢但正确的方法是:
void *myfunction() {
int *x = malloc(sizeof(int));
*x = 5;
return x;
}
Please never, ever write code like this, though.
但是,请永远不要写这样的代码。
回答by Valeriy
I compiled this source with gcc -pedantic:
我编译了这个源代码gcc -pedantic:
#include <stdio.h>
void *myfunction() {
size_t x = 5;
return (void*)x;
}
int main() {
printf("%d\n", *(int*)myfunction());
return 0;
}
There is no warnings
没有警告

