> // I don't understand this line. there is no & operator
Well fun(array); and fun(&array[0]); are the same thing.
Arrays, when passed as a function parameter decay to being a pointer to the first element of the array.
Question 6.3
A reference to an object of type array-of-T which appears in an expression decays (with three exceptions) into a pointer to its first element; the type of the resultant pointer is pointer-to-T.
Because all you get is a pointer, it's usual to also supply the size as an additional parameter.
Code:
void fun(int *pointer, size_t size)
{
for ( size_t i = 0; i < size; i++)
printf("%d ", pointer[i]);
}
int main()
{
int array[] = {1, 2, 3, 4, 5};
fun(array,5);
return 0;
}
> Why we can't write fun(&array) instead of fun(array)
You can!
But it's a different kind of pointer.
It's a pointer to the WHOLE array, not just one element of the array.
It looks like this.
Code:
// pointer is a pointer to an array of 5 ints
void fun(int (*pointer)[5], size_t size)
{
for ( size_t i = 0; i < size; i++)
printf("%d ", (*pointer)[i]);
}
int main()
{
int array[] = {1, 2, 3, 4, 5};
fun(&array,5);
return 0;
}
You have to be careful with the positioning of the parentheses.
int (*pointer)[5] is NOT the same as int *pointer[5].