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

Dynamic Two-Dimensional Array of Pointers

This topic is 5180 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
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;
The key there is the multiply followed by the add. It''s actually what the compiler does for you with statically allocated multidimensional arrays.

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



[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