开发者

Returning strings in C function, explanation needed

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 开发者_如何学Cfrom a high-level languages world, but this seems to be equally valid to me:

int x = 1;
return x;

char x[] = "hello";
return x;


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 x1 - 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;
}


1. This is a consequence of a special case rule for array types. In an expression, if an array isn't the subject of either the unary & 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.


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.


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.


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:

  1. Declare that char array to be static
  2. Allocate the buffer in the calling function, passing it as an argument, then this function just fills it.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜