• Welcome to Overclockers Forums! Join us to reply in threads, receive reduced ads, and to customize your site experience!

C++ Multidimensional Array

Overclockers is supported by our readers. When you click a link to make a purchase, we may earn a commission. Learn More.

thef0x82

Member
Joined
Jul 11, 2002
Location
Nebraska
Okay, here's the catch, I'm trying to declare a 2-dimensional array dynamically.
The line:

mymatrix = new int[x][y]

doesn't work. What's the correct syntax?
 
I can give you the way I'd do that in C, which should also work in C++.

A multidimensional array is simply an "array of arrays." You'll understand it better once you start working with pointers.

Declaring the array is quite simple:

int bah[x][y];

where x and y are ints.

Now, if you want to use dynamic memory managament here, I'm not quite sure on the "proper" C++ way to do that. In C, I'd just use malloc() and free(), but I don't believe you should need those in C++.
 
My C++ is incredibly rusty, but would something like the following work?
Code:
int** DynArray = new int *[4];
		
	for(int i=0; i < ArraySize; i++)
		DynArray[i] = new int[4];
 
heh, funny thing you asked this, just this morning I was working on an engineering assignment for c++, and had to declare a dynamic 2d array.

I used vectors to do it, as I find them easier to pass to procedures, not exactly what you need, but I can give you the code if you like.
 
Back