E
Eric Sosman
Keith said:[snip]Vincenzo Mercuri said:Il 16/08/2012 20:10, Varun Tewari ha scritto:
In 1, you actually duplicating the array in the funciton.
in 2, rather you are happy using a reference to the array, hence no duplication.
Wrong, AFAIK the only way to "pass an array by value" is by using a common
"trick": declare an array inside a struc and pass that struct as argument
to a function:
Yes, but you can only do that with arrays whose size is known at
compile time (you can't have a VLA as a struct member), which limits
its usefulness.
You could use a flexible array member instead, which would come to much
the same thing. (Or the infamous C89 "struct hack", which as far as I
know was never guaranteed to work, but which does in every C compiler
anyone's tested.)
Neither will work for the purpose of passing an array by value.
Concerning the flexible array member, 6.7.2.1p18 says
In most situations, the flexible array member is ignored.
In particular, the size of the structure is as if the
flexible array member were omitted except that it may have
more trailing padding [...]
In other words, the size of the called function's parameter -- the
"local variable" that stores the caller's argument value -- does
not include the flexible array, so there's no place for the callee
to store that array's value.
Same problem with the struct hack: Only the declared part of
the hacked array (usually of size [1]) is actually part of the
struct. Pass the struct by value, and only that declared part of
the hacked array is part of the value; any extra stuff is not
passed because (as far as the language knows) it's not even there.