Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you make sense of the error: cannot convert from 'int []' to 'int []'

When compiling the following code:

void DoSomething(int Numbers[])
{
    int SomeArray[] = Numbers;
}

the VS2005 compiler complains with the error C2440: 'initializing' : cannot convert from 'int []' to 'int []'

I understand that really it's trying to cast a pointer to an array which is not going to work. But how do you explain the error to someone learning C++?

like image 495
Craig Delthony Avatar asked Nov 27 '22 06:11

Craig Delthony


2 Answers

Say that there are types and incomplete types:

struct A;

Is an incomplete type of a struct called A. While

struct A { };

Is a complete type of a struct called A. The size of the first is not yet known, while the size of the second is known.

There are incomplete class types like the above struct. But there are also incomplete array types:

typedef int A[];

That is an incomplete array type called A. Its size is not yet known. You cannot create an array out of it, because the compiler does not know how big the array is. But you can use it to create an array, only if you initialize it straight away:

A SomeArray = { 1, 2, 3 };

Now, the compiler knows the array is an int array with 3 elements. If you try to initialize the array with a pointer, the compiler will not be any more clever than before, and refuse, because that won't give it the size of the array to be created.

like image 163
Johannes Schaub - litb Avatar answered Dec 05 '22 10:12

Johannes Schaub - litb


In trying to make the error message more helpful, the compiler is actually confusing things. Even though the Numbers parameter is declared as an array, C/C++ do not (cannot) actually pass an array - the Numbers parameter is actually a pointer.

So the error really should say "cannot convert from 'int *' to 'int []'"

But then there would be confusion - "hey, there's no int* involved in the expression", someone might say.

For this reason it really is better to avoid array parameters - declare them as pointers, since that's what you're really getting anyway. And the explanation to someone learning C/C++ should educate them on the fact that array parameters are a fiction - they're really pointers.

like image 22
Michael Burr Avatar answered Dec 05 '22 11:12

Michael Burr