Hi,guys how are you
I just want to ask in c programming that how to return a string to a main function


9 Years
Discussion Span
Last Post by Rashakil Fol

1. It's the caller responsibility to allocate space, then call the function with the string and the size of where to store the result. fgets() works like this.

2. The called function returns a pointer to a static string. asctime() works like this.
The downside is the caller needs to copy the result elsewhere before calling asctime() again.

3. The called function allocates memory and returns that pointer. The non-standard strdup() works like this.
The downside is the caller needs to free that memory at some point.


If I may I would like to make an observation.
In order to return a string from a function to main, is necesary an understanding of pointer variables and variable scope.

This code will never work:

#include <stdio.h>

char *mystring()
    char s[] = "I don't see the point";
    char *ptr = s; /* points to a local string */
/* after the function is finished the local string is destroyed
and this pointer will point to garbage */
    return ptr; 
int main( void )
    char *pointer;
    pointer = mystring();
    printf( "\"%s\"\n", pointer ); /* garbage will be printed here */
    return 0;    


char s[] = "I don't see the point";

into a

static char s[] = "I don't see the point";

will ensured that it will stay around after the function is finished. And therefore, the pointer ptr will have something correct to point to.



I'd add

4. Caller makes a char*, passes a pointer to the char** to the callee, and the callee sets the caller's char* to point to some freshly allocated memory, with the caller's responsibilty to clean up. Maybe return the string length or something useful as the return value. I prefer this to option 3.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.