Jump to content
  • Advertisement

Archived

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

zip_256

Dynamic array creation

This topic is 5433 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
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

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

Don''t forget to release the memory.

void Myclass::Release( )
{
for( int i=0;i < width;i++ )
{
delete [ ]cm_Myarray[ i ];
}
delete [ ]cm_Myarray;
}


Share this post


Link to post
Share on other sites
Do you have to declare the array in the main class declaration also to make it in scope of all the other class functions?

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!