Dynamic array creation

Started by
3 comments, last by zip_256 20 years, 8 months ago
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.
I am not a vegetarian because I love animals; I am a vegetarian because I hate plants.-Brent
Advertisement
void Myclass::Init (int width, int height)
{
cm_Myarray = new int*[width];
for (int i = 0; i < width; i++)
{
cm_Myarray = new int [height];
}
}

Hope this helps
Richard DickersonPikestriker Games "Kids you tried hard and failed miserably, lesson learned never try" - Homer Simpson
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]

Don''t forget to release the memory.

void Myclass::Release( )
{
for( int i=0;i < width;i++ )
{
delete [ ]cm_Myarray;<br> }<br> delete [ ]cm_Myarray;<br>}<br><br><br>
I am a Chinese spare time game developer and I hope to make mores friends to talk about game developing!
Do you have to declare the array in the main class declaration also to make it in scope of all the other class functions?
I am not a vegetarian because I love animals; I am a vegetarian because I hate plants.-Brent

This topic is closed to new replies.

Advertisement