2
votes

I'm trying to return a pointer to a character array. The function is located in a different file. I compile the files together and it prints out "hello" just fine, but still produces a warning

warning: assignment makes pointer from integer without a cast [enabled by default]

I tried casting the returned value of function() to (char *), but ended up with a different warning:

warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]" instead.

What am I doing wrong?

File 1

#include <stdio.h>                                                                                        

int main()                                                                                                
{                                                                                                                                                                                                   
   printf("%s\n", function());                                                                                   
   return 0;                                                                                               
}

File 2

#include <stdio.h>                                                                                       

char *message = "hello";                                                                                 

char *function()                                                                                         
 {                                                                                                        
  return(message);                                                                                       
 }                                                                                                        
1

1 Answers

4
votes

The problem here is a missing prototype. For historical reasons C lets you use functions without declaring them. However, all such functions are considered returning int, and all their parameters are considered int as well.

Since your function returns char*, you need to add a prototype for it (it's a good idea to have prototypes for all your functions, including ones that indeed return an int):

#include <stdio.h>                                                                                        

char *function(); // <<== Add this line

int main()                                                                                                
{                                                                                                                                                                                                   
   printf("%s\n", function());                                                                                   
   return 0;                                                                                               
}