howto resize a 2d array (C++)?

bignateyk

Lifer
Apr 22, 2002
11,288
7
0
How would I resize a 2d array in c++? I googled for it, but couldnt find anything...

I tried using the array.resize command but I couldnt get it to work.

Say I have

double myArray[2][2];

how would I resize that to

myArray[x][y];

Thanks,

-Nate
 

Oogle

Member
Feb 18, 2002
63
0
0
You need to delete and renew all of x in a for loop. For each x, repeat the same delete/renew process for each y in another for loop. In other words, it's a major PITA. Use a 2d vector. It'll save you a lot of resizing headaches.
 

glugglug

Diamond Member
Jun 9, 2002
5,340
1
81
If it's declared statically as above, you can't resize it.

You need to instead use a double ** (pointer to pointer to double, a.k.a. array of arrays of doubles)

1. Free unused rows if x > old x.
2. resize the inner arrays to your new y dimension
3. then resize the main array to your new x dimension.
4. allocate inner arrays towards the end of main array if y > old y.

Or as Oogle suggested, you can use a vector<vector<double>>
 

Barnaby W. Füi

Elite Member
Aug 14, 2001
12,343
0
0
Yeah, if you're using c++ you really should use the standard library to its fullest potential, vectors and lists and strings and all that.