General Question -- Dynamic 2D Array

G

Guest

Hello, all:

Just a general question that's been bothering me. Suppose I'd like to
create a 2D array of integers -- not using the vector template -- but I need
to dynamically create the array as I do not know the dimensions.

How could I do this using the "new" operator?

For instance, suppose I need to create an array of size row x column, but I
don't know the values being passed into the function...

I've tried it this way...

MyFunc(int nRow, int nCol)
{
int *array = (int *)new int[nRow][nCol];
...
delete [] array;
}

This seems to work for me, but a friend has told me this is -- perhaps --
unwise to do it that way. Any suggestions?

P.S. If there are multiple ways, could you select the way that would allow
me to access an element in the array by the following... array[1][2] =
blagh; That way I could easily access an element.

P.P.S. How would I delete the array as well?

Thank you, all.
 
G

Guest

Just declare the array as an array, not as a pointer:

int[,] array = new int[nRow][nCol]:
P.P.S. How would I delete the array as well?

You don't. You just let it go out of scope, and it will be garbage collected.
 
G

Guest

I should mention that this is C++.

Guffa said:
Just declare the array as an array, not as a pointer:

int[,] array = new int[nRow][nCol]:
P.P.S. How would I delete the array as well?

You don't. You just let it go out of scope, and it will be garbage collected.
 
R

Randolpho

I should mention that this is C++.

We assumed you meant *managed* C++ or C++/CLI, since you posted to the
..NET newsgroup. If this is for native/unmanaged c++, you should
probably post to another newsgroup.
 
G

Guest

There are two ways I know of to deal with this problem. One of them is just
to create a 1D array and do the 2D index math yourself:

#define INDEX2D(col, row, cols) ((col) + (row) * (cols))

MyFunc(int nRow, int nCol)
{
int *array = new int[nRow * nCol];

// to index col x, row y:
int n = array[INDEX2D(x, y, nCol)];
...
delete [] array;
}

The other way is to create a class to encapsulate a 1D dynamic array with an
overloaded operator[]. Template classes work really well for this. Then you
could create the 2D array like this:

MyDynArrayClass< MyDynArrayClass<int> > array;

and you would be able to index it like a regular array like this:

array[x][y];
 

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

Top