I am a c++ newbie. While learning I came across this.
if I have a pointer like this
int (*a)[2][3]
cdecl.org describe this as declare a as pointer to array 2 of array 3 of int:
When I try
int x[2][3];
a = &x;
this works.
My question is how I can initialize a when using with new() say something like
a = new int [] [];
I tried some combinations but doesn’t get it quite right.
Any help will be appreciated.
It’s probably not the answer you’re looking for, but what you
need is a new expression whose return type is
(*)[2][3]Thisis fairly simple to do; that’s the return type of
new int, for example. Do this, and[n][2][3]
awill point to thefirst element of an array of [2] of array of [3] int. A three
dimensional array, in sum.
The problem is that
newdoesn’t return a pointer to the toplevel array type; it returns a pointer to the first element of
the array. So if you do
new int[2][3], the expressionallocates an array of 2 array of 3 int, but it returns
a pointer to an array of 3 int (
int (*a)[3]), because in C++,arrays are broken (for reasons of C compatibility). And there’s
no way of forcing it to do otherwise. So if you want it to
return a pointer to a two dimensional array, you have to
allocate a three dimensional array. (The first dimension can be
1, so
new [1][2][3]would do the trick, and effectively onlyallocate a single
[2][3].)A better solution might be to wrap the array in a
struct:You can then use
new Array, and everything works as expected.Except that the syntax needed to access the array will be
different.