Skip to main content
gamedev.net
🔒 Locked

c++ dynamic 2D array

Started by HeadInjury11 Mar 23, 2003 at 8:21 PM 4 replies 250+ views
Original Post
HeadInjury11
HeadInjury11
greetings how do I dynamically allocate memory for the rows and the columns in a 2Darray/matrix?
YoshiN
YoshiN
I believe it''s something like this (I haven''t tested this code and it has been a while since I''ve done it):


  
// to create a 10x10 matrix

int **matrix;
matrix = new int *[10];
for(int i=0; i<10; ++i)
matrix[i] = new int[10];

matrix[0][5] = 1;
//...

-YoshiXGXCX ''99
YoshiN
YoshiN
AP beat me to it
-YoshiXGXCX ''99
David ONeil
David ONeil
The ways posted will work, but if an exception is thrown in your program between the time the array is constructed and destructed the memory will not be freed unless you add some major ''try'' - ''catch'' blocks. A way around this is to use the STL and maybe do something of the following:


  
#include <vector>

class MyArray {
private:
int numRowsC;
int numColsC;
std::vector<std::vector<int> > arrayC;
public:
MyArray(int rows, int cols) : numRowsC(rows), numColsC(cols) {
arrayC.reserve(numColsC);
for (int i=0; i<numColsC; ++i) {
arrayC.push_back(std::vector<int>());
std::vector<int> & temp = arrayC.back();
temp.reserve(numRowsC);
for (int j=0; j<numRowsC; ++j) temp.push_back(int());
}
}

std::vector<int> & operator[](int i) { return arrayC[i]; }
};


int main() {
MyArray arr(10, 10);
arr[0][0] = 5;
int junk = arr[0][0];
return 0;
}



Templatize the above (or something similar) for further ease of use.

Topic Locked

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

Sign in to reply to this topic.