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.

Mishrito
  • 51
  • 2

3 Answers3

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";
}
Sadique
  • 22,572
  • 7
  • 65
  • 91
  • 3
    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. – Fred Foo Sep 25 '13 at 14:01
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.

Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
  • 1
    Same comment that I posted under the other answer: prefer `const char*` when returning pointers to string literals. – Fred Foo Sep 25 '13 at 14:03
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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Srini Vas
  • 115
  • 1
  • 10