const int * is incompatible with const int (*)[10]

113 views Asked by At

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?

2

There are 2 answers

2
user12002570 On

The type of ptrArray is const int*( note thatarr[0] is const int so the type of &arr[0] is const int*). But since the function parameter is of type const int(*array)[10] and you're passing an argument of type const 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:

const int(*ptrArray)[10] = &arr; //or just auto ptrArray = &arr;
printArray(ptrArray); //works 
0
Vlad from Moscow On

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.

And what was changed?:) In both cases, you have a pointer of the type const int * that points to the first element of the array.

You need to pass a pointer to the whole array like this:

printArray( &arr );

And within the function, you should dereference the passed pointer:

void printArray(const int(*array)[10])
{
    cout << sizeof( *array ) << endl;
                    ^^^^^^
}

Otherwise, the function will output the size of the pointer itself instead of the size of the array.

Instead of a pointer, you could use a reference. For example:

void printArray(const int (&array)[10] )
{
    cout << sizeof(array) << endl;
}

//...

printArray( arr );