Re: why cant functions return arrays




"Hallvard B Furuseth" <h.b.furuseth@xxxxxxxxxxx> wrote in message
news:hbf.20080415l0zd@xxxxxxxxxxxxxxxx
sanjay.vasudevan@xxxxxxxxx writes:
Why are the following declarations invalid in C?
int f()[];
int f()[10];

Probably because of the language (mis)feature that array expressions
often decay to pointers to the first element of the array.

What would you do with that function? The 2nd variant:
int a[10] = f();
would presumably be a case of assigning the contents of an array to
another array, which C does not support. This won't compile either:
int a[10], b[10];
void foo() { a = b; }

Or if you would do this:
foo() { int *a; ... { ... a = f(); ... } }
then there is still an array-to-array assignment going on, only this
time to a temporary variable on the stack. However in this case it's
worse: The compiler may not be able to tell when the temporary becomes
"dead" so the space can be reused. It'd have to keep it around until
the function returns. This is because it created a pointer to the
temporary, which it won't do with other kinds of temporaries.

*a is a pointer to int. f() returns an array of int. So there is a type
mismatch and this should not compile, and the problem would not arise. I
don't think you can reasonably expect an array returned by a function to
'decay' to a pointer in the same way as a normal array.

(Creating a pointer to a value returned by a function is not a good idea
anyway, array or not)

--
Bart




.



Relevant Pages

  • Re: Warning on assigning a function-returning-a-pointer-to-arrays
    ... This declares pfunc as a function taking no arguments and returning ... int x, y; ... Presumably pfuncwill return a pointer to a single int, ... or the first of a sequence of "array 5 of int"s. ...
    (comp.lang.c)
  • Re: Newbie
    ... to talk about the int value 3 and the int value 4, ... It also lets you talk about pointer ... C has a special rule for array objects. ... to printf() is: ...
    (comp.lang.c)
  • Re: union {unsigned char u[10]; ...}
    ... But character type is not a union. ... u.a is of type int. ... has to do so to make pointer equality work consistently). ... were a single-element array. ...
    (comp.lang.c)
  • Re: How to pass a pointer to an unknown-size array?
    ... > I can pass a "pointer to a double" to a function that accepts ... > int func{ ... > Now I want to pass a pointer to an array of doubles, ...
    (comp.lang.c)
  • Re: union {unsigned char u[10]; ...}
    ... But character type is not a union. ... u.a is of type int. ... has to do so to make pointer equality work consistently). ... were a single-element array. ...
    (comp.lang.c)