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