Jump to content
  • Advertisement

Archived

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

TheGatekeeper

Dynamic Two-Dimensional Array of Pointers

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

So, how do I make one? I know there is an article that does something simaler, but that for C, I''m talking C++. I need a two-dimensional array of pointers, which is allocated at run-time. Can anybody give me a hand? I tried to search to see if this had been asked before, the the search seems broken. Thanks in advance!

Share this post


Link to post
Share on other sites
Advertisement
Well, there''s a couple of ways to make them, one of which is slightly more resistant to memory fragmentation.

In practice, though, professional programmers never do that. Instead, they allocate a one-dimensional array and treat it as multidimensional.

Say I want a 2D array of ints, of size 50x100. Then, I want to set the element at a particular x and y position to three. Here''s how I''d do that.


int width = 50;
int height = 100;
int x = 23; // or whatever

int y = 76; // or whatever


int* myArray = new int[rows * columns];
myArray[y*width + x] = 3;
[/quote]
The key there is the multiply followed by the add. It''s actually what the compiler does for you with statically allocated multidimensional arrays.
myArray[



How appropriate. You fight like a cow.

Share this post


Link to post
Share on other sites
If you just want a 2 demensional array of pointers you could do:

// allocate

int **test=new int*[ width ];
for(int i=0;i<width;i++)
test[ i ]=new int[ height ];

// de-allocate


for(int i=0;i<width;i++)
delete[ ] test[ i ];
delete[ ] test;

But just allocating a one-dimensional array is ussually better. Or, if the size of it is going to change you could just use a vector:

std::vector> test;

// add some integers

test.push_back(std::vector());
test[0].push_back(21);
test[0].push_back(44);

test.push_back(std::vector());
test[1].push_back(3);
test[1].push_back(52);




[edited by - brassfish89 on October 11, 2003 5:47:54 PM]

[edited by - brassfish89 on October 11, 2003 5:48:27 PM]

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!