Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

warning: return makes pointer from integer without a cast but returns integer as desired

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.

like image 375
user2662982 Avatar asked Aug 08 '13 03:08

user2662982


2 Answers

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;
}
like image 110
user2663103 Avatar answered Sep 20 '22 00:09

user2663103


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

like image 41
aaronman Avatar answered Sep 22 '22 00:09

aaronman