Dynamic Two-Dimensional Array of Pointers

Started by
1 comment, last by TheGatekeeper 20 years, 6 months ago
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!
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 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.
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]

This topic is closed to new replies.

Advertisement