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

c++ dynamic 2D array

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