In my understanding array
in int array[]={1,2,3,4,5}
is just a pointer to the first element of array
. It means that array
can be assigned to a pointer ptr
of type int*
.
Parameter int* &p
in hoo
will pass the argument by reference. It means we can change the passed argument to point to another value from within the hoo
.
void hoo(int* &p, int n)
{
for (int i = 0; i < n; i++)
cout << p[i] << endl;
}
int main()
{
int array[] = { 1,2,3,4,5 };
// I can do this
int* ptr = array;
hoo(ptr, 5);
// but not this.
//hoo(array, 5);
}
Why can't we pass int array
to hoo
without ptr
?
In my understanding array in int array[]={1,2,3,4,5} is just a pointer to the first element of array.
This is not correct. Arrays are arrays and pointers are pointers. They are distinct types with distinct properties. They are often confused because an array has the property that it will eagerly decay to a pointer to its first element.
hoo(array, 5);
tries to convert array
to an int*
but the result of that conversion is an rvalue and can't be bound to a non-const
reference. If, for example, you changed hoo
to take a const
reference it will compile fine :
void hoo(int* const &p, int n) { }
int main()
{
int array[] = { 1,2,3,4,5 };
hoo(array, 5);
}
In that case, you cannot change what p
points to, making the use of a reference pointless.