Your intuition is absolutely correct and, usually, you'd be right.
However, as a throwback to C, giving the name of an array as a function argument is a special and messy case — the name automatically transforms (or "decays") into a pointer to the array's first element.
So this:
void foo(int array[]);
actually means this:
void foo(int* array);
and so, even, does this:
void foo(int array[5]);
This cataclysmic design decision stemmed from the fact that arrays themselves cannot be automatically copied and somebody didn't want to keep writing out &myArray[0]
in full.
One way around it is to use the wrapper std::array
, which can be copied:
#include <array>
void foo(std::array<int, 5> name) // pass-by-value; copies!
{
name[3] = 8;
}
int main()
{
std::array<int, 5> array = { 1,2,3,4,5 };
foo(array);
// array is still 1,2,3,4,5 here
}
But, unless you are happy to delve into templates, you have to know the array dimension for that to work... and even if foo
were a function template, the dimension would still have to be known at compile-time.
The container std::vector
is a resizable array-like type with runtime dimensions; if your array won't always be 10 large, that may be what you need.