Moomin
Moomin

Reputation: 1926

Initialization of 2D array with dynamic number of rows and fixed number of columns. C++

I'm having problem with creating my 2D dynamic array in C++. I want it to have dynamic number (e.g. numR) of "rows" and fixed (e.g. 2) number of "columns".

I tried doing it like this:

const numC = 2;
int numR;
numR = 10;
double *myArray[numC];
myArray = new double[numR];

Unfortunately, it doesn't work. Is it possible to do it in such a way?

Of course I could use double **myArray and initialize it as if both dimensions are dynamic (with numC used as limiter in loop) but I would like to avoid it if possible.

Thanks in advance.

Upvotes: 3

Views: 6453

Answers (4)

fredoverflow
fredoverflow

Reputation: 263128

Is it possible to do it in such a way?

Yes:

double (*myArray)[numC] = new double[numR][numC];
// ...
delete[] myArray;

This may look a little unusual, but 5.3.4 §5 clearly states:

the type of new int[i][10] is int (*)[10]

Note that many programmers are not familiar with C declarator syntax and will not understand this code. Also, manual dynamic allocation is not exception safe. For these reaons, a vector of arrays is better:

#include <vector>
#include <array>

std::vector<std::array<double, numC> > vec(numR);
// ...
// no manual cleanup necessary

Replace std::array with std::tr1::array or boost::array, depending on your compiler.

Upvotes: 6

Cameron
Cameron

Reputation: 98756

There needs to be a loop since you need to create an array for every column.

I think what you're after is:

double *myArray[numC];
for (int i = 0; i < numC; i++) {
    myArray[i] = new double[numR];
}

// some code...

// Cleanup:
for (int i = 0; i < numC; i++) {
    delete [] myArray[i];
}

This declares an array of pointers (to double) with numC elements, then creates an array of doubles with numR elements for each column in myArray. Don't forget to release the memory when you're done with it or you'll have memory leaks.

Upvotes: 1

MahlerFive
MahlerFive

Reputation: 5279

Your indexes should be row, then column.

double** myArray = new double*[numR];
for( unsigned int i = 0; i < numR; i++ ) {
    myArray[i] = new double[numC];
}

Access row 2, column 5:

myArray[2][5];

Upvotes: -1

luke
luke

Reputation: 37463

Why not use a std::vector, and take advantage of its constructor:

std::vector<std::vector<int> > my2Darray(2, std::vector<int>(10));
my2Darray[0][0] = 2;

Upvotes: 2

Related Questions