#### Archived

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

# 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.

## 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 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 whateverint y = 76; // or whateverint* 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 on other sites
If you just want a 2 demensional array of pointers you could do:
// allocateint **test=new int*[ width ];for(int i=0;i<width;i++)    test[ i ]=new int[ height ];// de-allocatefor(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 integerstest.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]

1. 1
2. 2
Rutin
24
3. 3
4. 4
JoeJ
16
5. 5

• 14
• 29
• 11
• 11
• 9
• ### Forum Statistics

• Total Topics
631773
• Total Posts
3002268
×