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

thanks.

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 */
    getchar();
    return 0;    
}

Making

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.

~~words~~

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.