Casting pointer to Array (int* to int[2])

First of all b is an array, not a pointer, so it is not assignable.

Also, you cannot cast anything to an array type. You can, however, cast to pointer-to-array.
Note that in C and C++ pointer-to-arrays are rather uncommon. It is almost always better to use plain pointers, or pointer-to-pointers and avoid pointer-to-arrays.

Anyway, what you ask can be done, more or less:

int (*c)[2] = (int(*)[2])new int[2];

But a typedef will make it easier:

typedef int ai[2];
ai *c = (ai*)new int[2];

And to be safe, the delete should be done using the original type:

delete [](int*)c;

Which is nice if you do it just for fun. For real life, it is usually better to use std::vector.

Leave a Comment

tech