Reputation:
How do I assign to a multi dimensional array without casting [][] to **? I have an example below. What I found was How do I declare a 2d array in C++ using new? but that uses int**
rather then new int[][4]
.
#include<cassert>
int a[8][4];
int*b = &a[0][0];
int*c = &a[2][0];
int*d = &a[0][2];
int main() {
//shows right side is closer
assert(d-b==2);
assert(c-b==8);
auto aa = new int[][4];
//set the right side, but is a syntax error
//aa[][0] = new int[8];
//type error
aa[0] = new int[8];
}
Upvotes: 0
Views: 157
Reputation: 6488
edit: https://stackoverflow.com/a/18723991/598940 indicates a = new int[][8]
is actually not legal.
From your comments, are you asking why a = new int[][8]
is legal but a[][4]
is not?
int[]
is a type expression representing the same as the type int*
. It exists (I believe) to allow for more descriptive type declarations (perhaps among other things)
void foo(int* x); // is x an array of ints? or just a pointer to a single one?
void foo(int[] x); // ah, ok -- x is intended to represent an array of ints
The value expression a[]
, on the other hand, has no meaning.
Upvotes: 0
Reputation: 153909
You should be getting an error on the line with the new
int[][4]
. There must be an expression inside the []
.
Otherwise, how can the compiler know how much to allocate.
(Some quick checks with VC++, which erroneously does accept this
expression, shows that it treats it as the equivalent of new
int[0][4]
, and allocates 0 bytes. It doesn't compile with
g++.)
And of course, you confuse things additionally by abusing
auto
. The one reason never to use auto
is that you don't
know the actual type, and auto
means you don't have to know it
(until you want to use the variable, of course). In this case,
you should definitely not use auto
, because the type is a bit
special, and you want your readers to know it:
int (*aa)[4] = new int[8][4];
Once you see this, it should be obvious that aa[0]
has type
int[4]
, and there's no way you can assign a pointer to it,
since it isn't a pointer.
Of course, in C++, you'd never write anything like this anyway.
You'd define a Matrix2D
class, and use it. (And it would
probably use a std::vector<int>
to get the memory, and
calculate the single index from the two you give. Internally,
of course, so you don't have to think about it.) There is, in
fact, never a case for using array new
.
Upvotes: 1
Reputation: 22542
Try
int (*array)[4] = (int (*)[4])malloc(sizeof(int) * 8 * 4);
now you can access up to
array[7][3];
Upvotes: 1