Creating Dynamic 2D Arrays

M

monkeydragon

#define MAX_TABLE = 1024;
BYTE* dynamic1D = new BYTE[SIZE];

later..

i want to create a dynamic 2d ARRAY like this:

[0][<dynamic1D[1]>]
[0][<dynamic1D[2]>]
[0][<dynamic1D[3]>]
.....
[0][<dynamic1D[SIZE]>]

[1][<dynamic1D[1]>]
[1][<dynamic1D[2]>]
[1][<dynamic1D[3]>]
.....
[1][<dynamic1D[SIZE]>]

.....


[MAX_TABLE][<dynamic1D[1]>]
[MAX_TABLE][<dynamic1D[2]>]
[MAX_TABLE][<dynamic1D[3]>]
.....
[MAX_TABLE][<dynamic1D[SIZE]>]

Thx,
!MKD! ('',)!
 
M

marcas

monkeydragon said:
#define MAX_TABLE = 1024;
BYTE* dynamic1D = new BYTE[SIZE];

later..

i want to create a dynamic 2d ARRAY like this:
Hi,
int main () {
int rows=10,cols=10;
int** mat = new int*[rows];
for (int i=0; i<rows; i++) mat=new int [cols];

//access example:
mat[2][3]=15;

//dont forget to free it after its not required any more
for (int i=0; i<rows; i++) delete[] mat;
delete[] mat;

return 0;
}

Another way would be using STL:

vector <vector<int>> mat (rows,vector<int>(cols));
mat[2][3]=15;

regards marcas
 
A

Axter

marcas said:
monkeydragon said:
#define MAX_TABLE = 1024;
BYTE* dynamic1D = new BYTE[SIZE];

later..

i want to create a dynamic 2d ARRAY like this:
Hi,
int main () {
int rows=10,cols=10;
int** mat = new int*[rows];
for (int i=0; i<rows; i++) mat=new int [cols];

//access example:
mat[2][3]=15;

//dont forget to free it after its not required any more
for (int i=0; i<rows; i++) delete[] mat;
delete[] mat;

return 0;
}

Another way would be using STL:

vector <vector<int>> mat (rows,vector<int>(cols));
mat[2][3]=15;

regards marcas


I recommend the vector method, but be carefull to add a space betwee >>
Should be the following:
vector <vector<int> > mat (rows, vector<int>(cols));

With the current C++ standard, you'll get a compile error if you don't
put the space between > >. They are considering changing this in a
future version of the standard.

Also take a look at the following links for other methods for creating
a dynamic 2D array:
http://code.axter.com/dynamic_2d_array.h
http://www.codeguru.com/forum/showthread.php?t=231046
http://www.codeguru.com/forum/showthread.php?s=&threadid=297838

C-Style compatible method:
http://code.axter.com/allocate2darray.h
http://code.axter.com/allocate2darray.c
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top