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.
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;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With