I’m working on a project of which I should store constant multi dimensional arrays.I would like to do it with a pointer which points to multi-dimensional arrays.However, I could’nt succeeded.I write this code but it didn’t compiled.
int darray[1][2];
int darray2[2][3];
int (*p)[1][2];
p= new int[2];
p[0] = darray;
p[1] = darray2;
Well, let’s go through your code line by line (OK, I’ll lump the first two lines together)
OK, this defines two two-dimensional arrays in exactly the way you (probably) expect. Note that formally, those are actually arrays of arrays of ints. More exactly,
darrayis of type “array of 1 array of 2 ints each”, and darray2 is of type “array of 2 arrays of 3 ints each”This defines a pointer to a two-dimensional array of int, or to the first element of an array of such arrays. That is, the type of
pis “pointer to array of 1 array of 2 ints each”.Here you are allocating space for two ints (i.e. an one-dimensional array of ints, of length two), and
newreturns a pointer to the first element of that array, i.e. a pointer to int. You try to assign that pointer to int top, which is a pointer to array of 1 array of 2 ints each, as mentioned above. This gives a type mismatch and should not compile.It’s not entirely clear what you want at that point, but given that you do assignments to
p[0]andp[1]afterward, and given that the return value is assigned topwhich is of typeint (*)[1][2]the obvious choice would bep = new int[2][1][2];This again doesn’t work, because arrays in C++ are not first-class objects. That is, instead of assigning the value of
darraytop[0]as the line would suggest (andp[0]indeed would have the right type for that) the rules of C++ say that the arraydarrayis promoted to a pointer to its first element. That is, what this code actually tries to do is to assign a pointer to the first element ofdarray(of typeint (*)[2]) top[0](of typeint[1][2]), which of course fails. In C++, arrays are simply not assignable.This suffers from the same problem, however note that even if arrays were first-class, assignable objects in C++, this still would be a type mismatch because
p[1]is of typeint[1][2]whiledarray2is of typeint[2][3].Note that you get around most of those limitations (apart from the last one) by just wrapping you array into a class C++11 actually provides a standard class template called
std::arrayfor this purpose):With a bit more of programming you could also handle the assignment from larger to smaller arrays (your
darray2case) by copying only part of the data by hand.