Reputation: 9935
I understand that in order to return a string from a function I have to return a pointer. What I don't understand is why a char array is treated somewhat different from, say, integer, and gets destroyed when you exit the function. That's probably because I come from a high-level languages world, but this seems to be equally valid to me:
int x = 1;
return x;
char x[] = "hello";
return x;
Upvotes: 2
Views: 1390
Reputation: 239011
The reason is both simple, yet subtle: C functions cannot be declared to return arrays.
When you return a pointer, like this:
char *foo(void)
{
char x[] = "hello";
return x;
}
The return x;
is not actually returning x
. It is returning a pointer to the first element of x
1 - it is exactly the same as saying:
return &x[0];
It should be more clear why this isn't correct - it is exactly analagous to this:
int *foo(void)
{
int x = 100;
return &x;
}
It is, however, possible to return structures from functions - so you can return an array as long as it wrapped inside a struct
. The following is quite OK:
struct xyzzy {
char x[10];
};
struct xyzzy foo(void)
{
struct xyzzy x = { "hello" };
return x;
}
&
or sizeof
operators, it evaluates to a pointer to its first element. Trying to pin down actual an array in C is a bit like trying to catch fog in your hands - it just disappears, replaced by a pointer.
Upvotes: 8
Reputation: 34592
Please see this detailed answer I have written about this. Not alone that, in C, variables that are created within the scope of functions are using an automatic stack heap where the variables will resides in and when the function returns, that heap is destroyed, this is where the usage of local variables especially of type string i.e. char [] or a pointer to string must be allocated on the heap outside of the function scope otherwise garbage will be returned. The workaround on that is to use a static buffer or use malloc
.
Upvotes: 2
Reputation: 117333
That char array is allocated within the scope of the function (rather than dynamically allocated eg by malloc()), so it will be unavailable outside of that scope.
Two ways around it:
static
Upvotes: 1
Reputation: 70701
An integer is a primitive type, so it's value is returned as such. However, in C, a string is not a primitive type, which is why you declare it as an array of characters. And when you return an array, you are actually returning a pointer to the original array, so it is a kind of return-by-reference, if you will. But as you can see, the pointer to char x[]
is invalid once you exit the function.
Upvotes: 3