3

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.

John Dibling
  • 99,718
  • 31
  • 186
  • 324
Moomin
  • 1,846
  • 5
  • 29
  • 47
  • 1
    What exactly isn't working? What is `threadAccelerationTable` and how does it relate to `myArray`? – Cameron Nov 23 '10 at 14:15

4 Answers4

6

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.

fredoverflow
  • 256,549
  • 94
  • 388
  • 662
2

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;
luke
  • 36,103
  • 8
  • 58
  • 81
1

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.

Cameron
  • 96,106
  • 25
  • 196
  • 225
-1

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];
MahlerFive
  • 5,159
  • 5
  • 30
  • 40