Skip to main content
GameDev.net gamedev.net
🔒 Locked

Dynamic Two-Dimensional Array of Pointers

Started by TheGatekeeper Oct 11, 2003 at 2:12 PM 1 replies 250+ views
Original Post
TheGatekeeper
TheGatekeeper
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!
Sneftel
Sneftel
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.
brassfish89
brassfish89
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]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.