Jump to content
  • Advertisement


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


c++ dynamic 2D array

This topic is 5721 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

Guest Anonymous Poster

int* c = new int[rows*cols];
c(x,y) = c[y*rows+x]


int** c = new int*[rows];
for (int i=0; i<rows; i++)
rows[i] = new int[cols];
c(x,y) = c[x][y];

the second one is slower to init

Share this post

Link to post
Share on other sites
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;

Share this post

Link to post
Share on other sites
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 {
int numRowsC;
int numColsC;
std::vector<std::vector<int> > arrayC;
MyArray(int rows, int cols) : numRowsC(rows), numColsC(cols) {
for (int i=0; i<numColsC; ++i) {
std::vector<int> & temp = arrayC.back();
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.

Share this post

Link to post
Share on other sites

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!