# Dynamic multidimensional arrays

## Recommended Posts

ive been fighting with msvc++ for the past few hours trying to figure out how make a 2d array. there is a trick to it though. one dimension (we will say its vertical) is resized only once. the other dimension (horizontal) will need to be different sizes. here is a drawing to help out:
[][][][][][]
[][][]
[][][][]
[][][][][]
[][][]
[][][][][]

my question is 1. is this possible? 2. if it is how do i define the array? thanks ahead of time

##### Share on other sites
In C# this is called a jagged array. In C++ there is no language or standard library support for this feature so you'd have to either develop one yourself or look for one on the internet. I would first take a look at boost as it's very likely to have this. If it doesn't, hit google and consider looking for related projects on sourceforge.

##### Share on other sites
You can't define an actual array like that, but you can get very close using the vector class:
#include <vector>vector< vector<int> > JaggedArray;
Then you could do JaggedArray.resize(_) to set the 'outer dimension' and then JaggedArray[0].resize(_) set the 'inner dimension' of the first 'horizontal'

##### Share on other sites
#include <vector>std::vector< std::vector<int> > jaggedArray;jaggedArray.resize(5);jaggedArray[0].resize(3);jaggedArray[1].resize(5);jaggedArray[2].resize(4);jaggedArray[3].resize(7);jaggedArray[4].resize(5);

##### Share on other sites
HELL YEAH!!! thanks alot d00ds
:bowdown:

##### Share on other sites
Quote:
 Original post by ExtrariusYou can't define an actual array like that, but you can get very close using the vector class:#include vector< vector > JaggedArray;Then you could do JaggedArray.resize(_) to set the 'outer dimension' and then JaggedArray[0].resize(_) set the 'inner dimension' of the first 'horizontal'

You can, the following will make the OP's example:
int **wmda = 0;wmda = new int*[6];wmda[0] = new int[6];wmda[1] = new int[3];wmda[2] = new int[4];wmda[3] = new int[5];wmda[4] = new int[3];wmda[5] = new int[5];

It is probably a better idea to use vectors, though, because the previous would be a nirvana for buffer-overflows, unless you made a wrapper class that implements bounds-checking -- which, by the way, vectors don't do if you use the [] operator (use vector::at() instead).

Regards,
jflanglois

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628308
• Total Posts
2981973

• 9
• 13
• 11
• 12
• 11