Reputation: 367
I'm trying to find out the proper way to return an integer from a void * function call within C.
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.
Upvotes: 10
Views: 68626
Reputation: 1435
I compiled this source with 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
Upvotes: 0
Reputation: 27105
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:
void *myfunction() {
int *x = malloc(sizeof(int));
*x = 5;
return x;
}
Please never, ever write code like this, though.
Upvotes: 0
Reputation: 121
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.
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.
void *myfunction() {
long x = 5;
return (void *)x;
}
Upvotes: 9
Reputation: 18750
A void * is a pointer to anything, you need to return an address.
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
Upvotes: 2