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?
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.
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]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With