0

Basically what I want is to return a string from a function (or an array in general).

type_string(?) Function_foo(type_string(?) string_foo)
{
     ......
    return String_bar;
}

printf("%s", function_foo(string_foo));

This should give me string_bar as output. Is that possible? All the questions I've looked at so far, give special usecases and the answers are specific to that.

1
  • 1
    Have you tried char* ? Commented Sep 25, 2013 at 13:59

3 Answers 3

2

Array will not work because if it is out of scope the object will cease to exist (unless allocated dynamically).

But this is fine:

char  * foo1()
{
  char *  p= "somestring"
  return p;
}

char  * foo2()
{
  return  "somestring";
}
Sign up to request clarification or add additional context in comments.

1 Comment

Using char* to point to literals is permitted by the C standard for historical reasons, but that doesn't make it a good idea. const char* is self-documenting, use that when the caller must not modify the string.
2

Strings do not exist as a type in C, they are char arrays. An array is basically a pointer to the first element. So, to return a string (or array), you return a pointer:

const char *function_foo(const char *string_foo)
{
    const char *String_bar = "return me";

    return String_bar;
}

const char *string_foo = "supply me";
printf("%s", function_foo(string_foo));

More information can be found on Wikipedia.

1 Comment

Same comment that I posted under the other answer: prefer const char* when returning pointers to string literals.
1

When you create a char[] and return it from a string, you actually get the memory for the char[] from the program stack. When your function returns, the char[] loses its scope and can contain a garbage value. So you should use malloc to locate the char *, so you will get memory from the heap, which you will have to free() in the calling function.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.