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 ?
Asked
Active
Viewed 386 times
1 Answers
6
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.

Community
- 1
- 1

Alok Singhal
- 93,253
- 21
- 125
- 158
-
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 Jan 19 '10 at 06:41
-
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 Singhal Jan 19 '10 at 06:43
-
Thanks Alok! Explanation in the pointed post was very helpful – cppdev Jan 19 '10 at 06:49
-
Where did you find this explanation of "value context" and "object context" ? Is there any book that explains such level of details ? – cppdev Jan 19 '10 at 06:52
-
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 Singhal Jan 19 '10 at 06:57