Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Shaun E on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dynamically creating multi-dimensional arrays

Status
Not open for further replies.

nexius

Programmer
Jul 8, 2000
109
CA
Hey, something that I don't understand:

I can use a non-constant integer to dynamically allocate space for a one-dimensional array, like so:

float *things = new float[num_of_things];

But the following will not compile:

float *things = new float[things_per_row][things_per_col];

Why is this? There's gotta be a way to dynamically create multi-dimenionsal arrays..... right?
 
nevermind...

I found an old thread with the same question

sorry
 
In C/C++, you can only have one variable dimension at a time. Basically you have to create it in stages. Alternatively, you can create it in one big chunk and point to it. eg to create a rows x cols array
Code:
int** twod = new int[rows];
twod[0] = new int[rows * cols];
for (int r = 1; r < rows; r++)
    twod[r] = twod[r - 1] + cols;

// now you can access twod[r][c]

// Note that destruction is slightly different
delete [] twod[0];
delete [] twod;
You don't need to go into a loop deleting bits of array.
 
xwb's example principally is correct, except of line
int** twod = new int*[rows];

Here is what the language specification proposes:

int (*twod)[cols];
twod = new int [rows][cols];

delete [] twod;
 
Oops! That's what happens when you type things in without running them through the compiler first [sad].
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top