tags:

views:

142

answers:

1

In C, arrays are passed to functions as pointers. Structures can be passed to functions either by value or by address (pointer). Is there any specific reason why we can not pass array by value but we can pass structre by value ?

+6  A: 

In C, everything is passed by value. There is another rule that says that in most contexts, the name of an array is equivalent to a pointer to its first element. Passing an array to a function is such a context.

So, the special case is not that arrays are passed by reference, the special case is the rule about arrays decaying to pointers. This gives one the impression that an array is passed by reference (which it effectively is, but now you know why!)

The post in my link above explains in more detail about the type of an array in different contexts.

Alok
Pointers are passed by val. int *p1, int *p2; p1 = p2; there are no references here. the address is copied from p2 to p1.
the_drow
Yes, pointers are passed by value, just like everything else. For arrays, the *effect* is as if they were passed by reference, but because of "the rule" about arrays decaying to pointers. Of course, the pointer value of the first element of the array is passed by value, but that doesn't matter in this case.
Alok
Thanks Alok! Explanation in the pointed post was very helpful
cppdev
Where did you find this explanation of "value context" and "object context" ? Is there any book that explains such level of details ?
cppdev
From reading `comp.lang.c`, then the standard. A really nice description is http://web.torek.net/torek/c/expr.html#therule. In fact, all of http://elf.torek.net/torek/c/ is very good.
Alok