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;
The reason is both simple, yet subtle: C functions cannot be declared to return arrays.
When you return a pointer, like this:
The
return x;is not actually returningx. It is returning a pointer to the first element ofx1 – it is exactly the same as saying:It should be more clear why this isn’t correct – it is exactly analagous to this:
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: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
&orsizeofoperators, 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.