Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why g++ gives error : cannot convert ‘int (*)[3]’ to ‘int (*)[]’ in initialization

When I try to compile the following code with g++:

int main()
{
    int a[3] = {0, 1, 2};
    int (* p)[] = &a;
}

compiler gives the following error : "cannot convert ‘int ()[3]’ to ‘int ()[]’ in initialization". Why isn't it possible to convert int ()[3] to int ()[]? And if it is not possible then how a variable of type 'int (*)[]' should be initialized?

like image 921
Hrant Avatar asked Dec 15 '22 09:12

Hrant


2 Answers

Because you have to specify the length of the array your pointer pints to. It should be like this:

int (* p)[3] = &a;

int (*p)[] this means that your p is a pointer to an array. The problem is the compiler has to know at compile time how long is the array that pointers points to, so you have to specify a value in the brackets -> int (*p)[x] where x is known at compile time.

like image 169
Alexandru Barbarosie Avatar answered May 15 '23 03:05

Alexandru Barbarosie


There are many ways to initialize a variable of type int (*)[]. For example, it can be initialized by other values of int (*)[] type (including ones produced by an explicit cast) or by null-pointer constant. An int (*)[3] value will not immediately work since it has a different type.

In your case I'd expect this to be perfectly legal and defined

 int (*p)[] = (int (*)[]) &a;

with further access to the afray as (*p)[i].

like image 31
AnT Avatar answered May 15 '23 01:05

AnT