Warning: return makes a pointer from an integer without casting, but returns an integer as desired

I am trying to find the correct way to return an integer from a call to the void * function inside 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 a pointer from an integer without cast

Is there a way to do this to make this work? It seems that it returns x without any problems, the real myfunction also returns pointers to structures and character strings that work as expected.

+7
c function casting integer void
source share
4 answers

It is not clear what you are trying to do here, but I assume that you are trying to do some pointer arithmetic using x and want x to be an integer for this arithmetic, but a pointer to void when returning. Without going into why this makes sense or doesn't make sense, you can eliminate this warning by explicitly pointing x to the void pointer.

 void *myfunction() { int x = 5; return (void *)x; } 

This will most likely trigger another warning, depending on how your system implements the pointers. You may need to use long instead of int.

 void *myfunction() { long x = 5; return (void *)x; } 
+5
source share

Void * is a pointer to anything, you need to return the address.

 void * myfunction() { int * x = malloc(sizeof(int)); *x=5; return x; } 

In this case, you do not need to return void * for int, you must return int * or even better just int

+1
source share

Although you think the easiest way to do this is:

 void *myfunction() { int x = 5; return &x; // wrong } 

this is actually undefined behavior, since x is allocated on the stack and the stack frame is β€œminimized” when the function returns. Stupid but correct way:

 void *myfunction() { int *x = malloc(sizeof(int)); *x = 5; return x; } 

Please, never, never write such code.

0
source share

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; } 

No warnings

0
source share

All Articles