3

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 ?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Pointers are passed by val. int *p1, int *p2; p1 = p2; there are no references here. the address is copied from p2 to p1.
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.
Thanks Alok! Explanation in the pointed post was very helpful
Where did you find this explanation of "value context" and "object context" ? Is there any book that explains such level of details ?
From reading comp.lang.c, then the standard. A really nice description is web.torek.net/torek/c/expr.html#therule. In fact, all of elf.torek.net/torek/c is very good.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.