Search code examples
cstringfunctionreturn

How to return a string from a function to main()?


I have tried the following code but am getting an error:conflicting types for fun.Is there any solution that doesn't require the use of malloc.

#include <stdio.h>
int main()
{
printf("%s",fun());
return 0;
} 

char* fun()
{
static char str[]="Hello";
return str;
}

Solution

  • It is because you have not declared prototype for fun.

    #include <stdio.h>
    char* fun(void);
    int main()
    {
       printf("%s",fun());
       return 0;
    }
    
    char* fun(void)
    {
       static char str[]="Hello";
       return str;
    }