0

When you pass an array to a function, does it allocate memory not for the array but for the address of the first element of the array?

zhm
  • 107
  • 7
  • The array you pass decays to a pointer to its first element, so yes. Even if the function is say `func(char arr[10])` a pointer is passed, and the function is equivalent to `func(char *arr)` – Weather Vane Jul 21 '22 at 12:38
  • Allocation for an array occurs at declaration. In passing an array as a function argument, there is no additional memory allocation, and as @weather vane has explained, the array object is not passed, only a pointer to the first element. – ryyker Jul 21 '22 at 12:45
  • There is a [good question/answer here](https://softwareengineering.stackexchange.com/a/318837/143513) that addresses your question. And a very good [discussion on stack memory here](https://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap). – ryyker Jul 21 '22 at 12:53

1 Answers1

0

All function arguments are passed on the stack (which is a memory space reserved for that purpose). Compiler optimisations might avoid stack usage by holding the values in registers, but you should work on the basis that the size of the argument is allocated to stack.

Note that in C, parameters are either integral values (int, char, etc) or pointers. Objects/Arrays are only ever a pointer to the first element/base (or pointer to pointer etc).

Dave Meehan
  • 3,133
  • 1
  • 17
  • 24
  • 2
    Structures are passed by value. Only arrays decay to a pointer. – Barmar Jul 21 '22 at 12:46
  • @barmar Quite true, but generally pass by value for anything other than integrals is considered sub-optimal. And yes, an array is never passed in its entirety, but always as a pointer which can be accessed with array notation. – Dave Meehan Jul 21 '22 at 12:55
  • An array is passed in its entirety if is a struct member that is passed by value. – Weather Vane Jul 21 '22 at 13:01
  • @DaveMeehan My point is that it doesn't automatically convert structures to pointers. If you want that, you have to do it explicitly with `&`. – Barmar Jul 21 '22 at 13:04