Archived

This topic is now archived and is closed to further replies.

Dynamic array creation

This topic is 5218 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello everyone. This is more of a C++ question than anything. I need to create a private, two dimensional array in a class after an initialization function of the class has been called to set the values of two private integers, the width and height of the array. I know there is probably a simple way to do this, but I have a really bad mental block at the moment.

Share this post


Link to post
Share on other sites
The easiest and best way is simply to allocate a one-dimensional array with the size being the product of the length and the width, and treat it like a two-dimensional array.


const int WIDTH = 50;
const int HEIGHT = 60;

int *array = new int[WIDTH * HEIGHT];

int row = 4;
int column = 3;

cout << "In row 4, column 3, there is " << array[row * WIDTH + column] << endl;


EDIT If you absolutely CANNOT LIVE WITHOUT THE STUPID DOUBLE-SUBSCRIPT and don't mind the inefficiency that this causes, don't use Pike's method, as it causes memory fragmentation. This works a bit better:

void Myclass::Init (int width, int height)
{
cm_Myarray = new int*[width];
cm_Myarray[0] = new int[width*height];
for (int i = 0; i < width; i++)
{
cm_Myarray[i] = cm_Myarray[0] + i*width;
}
}


How appropriate. You fight like a cow.

[edited by - sneftel on September 3, 2003 12:08:11 AM]

Share this post


Link to post
Share on other sites