Dynamic array creation
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.
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
{
cm_Myarray = new int*[width];
for (int i = 0; i < width; i++)
{
cm_Myarray = new int [height];
}
}
Hope this helps
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.
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:
How appropriate. You fight like a cow.
[edited by - sneftel on September 3, 2003 12:08:11 AM]
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>
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement