Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2D int array in C++

So I want to initialize an int 2d array very quickly, but I can't figure out how to do it. I've done a few searches and none of them say how to initialize a 2D array, except to do:

int [SOME_CONSTANT][ANOTHER_CONSTANT] = {{0}};

Basically, I've got 8 vertices, and I'm listing the 4 vertices of each face of a cube in an array. I've tried this:

int[6][4] sides = {{0, 1, 2, 3}, {4, 5, 6, 7}, {0, 4, 7, 3}, {7, 6, 2, 3}, {5, 1, 2, 6}, {0, 1, 5, 4}};

But that tells me that there's an error with 'sides', and that it expected a semi-colon. Is there any way to initialize an array quickly like this?

Thanks!

like image 445
Casey Kuball Avatar asked Dec 06 '25 06:12

Casey Kuball


1 Answers

You have the [][] on the wrong side. Try this:

int sides[6][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}, {0, 4, 7, 3}, {7, 6, 2, 3}, {5, 1, 2, 6}, {0, 1, 5, 4}};

Keep in mind that what you really have is:

int **sides

(A pointer to a pointer of ints). It's sides that has the dimensions, not the int. Therefore, you could also do:

int x, y[2], z[3][4], ...;
like image 86
Derek Springer Avatar answered Dec 08 '25 19:12

Derek Springer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!