Link to home
Start Free TrialLog in
Avatar of perlperl
perlperl

asked on

retunr type

can someone give me a simple example of a function whose return type is string or character array?
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
And with the body :

    char *returnString() {
        char *str = calloc(10, sizeof(char)); /* creating a 9-character string on the heap */
        /* filling up the string here ... */
        return str;
    }

Call it like this :

    char *myString = returnString(); /* call the function which returns the string */
    /* use the string */
    free(myString); /* don't forget to clean up the string once you don't need it any more, or you have a memory leak */
I think the usual convention is create a buffer first (either using the heap or stack), then pass a pointer to the buffer as an argument to the function so the function can modify it directly. This allows the function to handle strings, regardless of the method of creation.

Getting to your question, if you want the function to return a string, the normal way is to create it on the heap (dynamic memory allocation), since the stack will be destroyed once the function exits and the pointer will reference memory that is no longer valid. In this scenario, the user is responsible for freeing up the memory used by the string once he/she is done.