3

I wonder why we can pass structure to C function by value, but we can never do the same with array (which is passed by address).

When I was learning C, they told me that arrays consume much stack, so it's not preferred to pass them by value.

But it seems that structures are often (if not always) larger than arrays and are more complex data structure, so this explanation makes no sense for me now !

Can anybody help with as much details as possible ?

Matt
  • 22,721
  • 17
  • 71
  • 112
Ahmed Adel
  • 331
  • 4
  • 10
  • This question has been asked before in c++ context but also applies to c [link](http://stackoverflow.com/questions/7454990/why-cant-we-pass-arrays-to-function-by-value) – Yarneo Sep 15 '12 at 21:27

1 Answers1

5

In C, an array is always defined as a pointer to the first position of the array, so by definition, when you are passing an array to a function your are passing its memory address, hence its reference.

When you define a variable of type struct, you're allocating all the space in memory needed to to contain this struct, and if you make something like:

struct a, b;
...
a = b;

You are copying all the values from b to a, and in the same way, when you are passing it to a function, you are copying the values of the original struct to the stack. That's called passing a parameter by value.

It's true what you're stating in your question. A struct may be more complex than an array, but it's perfectly possible to pass it as value, and it may be inefficient, but the reason that you can't pass an array by value is because it is defined as a pointer by default.

Hernan Velasquez
  • 2,770
  • 14
  • 21
  • 1
    +1 with the comment that arrays are not "defined by pointers", they rather decay to pointers when passed to functions. –  Sep 15 '12 at 21:27