Question:

I wanted to know how we could return a string from a function in c language

by  |  earlier

0 LIKES UnLike

I wanted to know how we could return a string from a function in c language

 Tags:

   Report

3 ANSWERS


  1. Well, if you want to return a static string, then

    char str = "this is a string";

    return str;

    works.  Or even

    return "this is a string";

    But that's probably not what you want.  You're probably want to return a string you've modified.  And the problem is that if you use an auto variable (stored on the stack) for the buffer for the string, it won't exists (or may get overwritten) the instant you return.  There are three ways to make this work.

    1. Have the caller provide the buffer.

    caller() {

    char buf[100];

    callee(buf);

    }

    callee(char *buf) {

    strcpy(buf, "hello, world");

    }

    Note that callee doesn't even have to pass the new string back. The caller already has the address where the result goes.

    2. The callee uses a static buffer.

    caller() {

    char *p;

    p = callee();

    }

    char *callee() {

    static char *buf[100];

    strcpy(buf, "hello, world");

    return buf;

    }

    Note that the buffer never goes away.  The storage lives for the life of the program.  Memory is cheap, right?  Another disadvantage is that if you call callee() again, the same buffer is used.  So the previous caller may still have a pointer to the new data - and the old data is gone.

    3. Dynamically allocated the buffer.

    caller() {

    char *p;

    p = callee();

    /* use the string p here */

    free(p);

    }

    char *callee() {

    char *buf;

    buf = malloc(100);

    strcpy(buf, "hello, world");

    return buf;

    }

    Note that if the caller doesn't free() the buffer, it will live in the heap for the rest of the program.  That might be OK, but it also might be considered a memory leak.  One advantage is that no matter how many times caller() is called, each returned string has it's own buffer.

    In Perl, "there's more than one way to do it", and they all work.  In C, you have to know what you're doing, what you're likely to do in the future, and so on.  And C will happily let you hack your leg off with a chain saw even if you only wanted a shave.  C is still the gold standard for speed.  This is partly due to the above choices you have.


  2. public string MyFunction()

    {

        return ""; // or whatever

    }

  3. suitti gave the perfect answer!

Question Stats

Latest activity: earlier.
This question has 3 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.