I am trying to understand why the following code does not work:
void printArray(const int(*array)[10])
{
cout << sizeof(array) << endl;
}
int main()
{
const int arr[10] = { 1, 2 };
const int* ptrArr = &arr[0];
printArray(ptrArr);
}
const int(*array)[10] -> array is a pointer to an array with 10 elements of type const int.
At first, I thought I could invoke the function with just arr, but it didn't work. Maybe the reason it does not work in this case is because arr doesn't point to an array, it points to the first element in an array.
That's why I decided to define a pointer, pointing to the first element of the array. What's the issue now though?
The type of
ptrArrayisconst int*( note thatarr[0]isconst intso the type of&arr[0]isconst int*). But since the function parameter is of typeconst int(*array)[10]and you're passing an argument of typeconst int*and there is no implicit conversion between the two, we get the mentioned error.Solution
To fix this, just remove the use of subsript when taking the address of the array as shown below: