# Two dimensional dynamically allocated array problem

• 08-19-2009
binaryboy
Two dimensional dynamically allocated array problem
Hi everyone.

I'm having some trouble with dynamically allocating a 2D array. Here's the portion of code dealing with it.

Code:

```myArrayOne = new int*[size]; for(int i = 0; i < size; ++i) {         myArrayOne[i] = new int[3]; }         for(int i=0;i<size;i++) {         for(int j=0;j<3;j++)         {                 myArrayOne[i][j] = 0;  // where program crashes         } }```
The program crashes and (I'm using VS2005) the error tells me that that expression cannot be evaluated. Now obviously I've made a mistake somewhere there but I can't spot it and this way seems to be working for other people judging from a google.

Any help appreciated.
• 08-19-2009
binaryboy
Ok problem solved. I had a different variable in for 'size' in the first for loop. Only saw it when posting up here.
• 08-19-2009
whiteflags
Ehh just so you know there is an easier way that involves some elementary pointer arithmetic.

Code:

```int main() {   int **myArray;   int rows = 10, cols = 3;   myArray = new int*[rows];   myArray[0] = new int[rows * cols];   for( int k = 1; k < rows; k++ ) {       myArray[k] = myArray[0] + (k * cols);   }   // use myArray   delete [] myArray[0];   delete [] myArray; }```
Basically the key part to this is the for loop. If you can correctly assign the pointers in the first dimension to their respective columns, like here, then you can use the familiar myArray[i][j] syntax with just two allocations to manage.

You will have to repeat this code when you reallocate for a bigger matrix.
• 08-19-2009
binaryboy
Interesting, it's been a long time since I've messed around with dynamic arrays and the likes. Cheers for the input.
• 08-19-2009
Daved
There's an even easier way. Use vector. Unless you're learning, there isn't much reason to use a dynamic array in C++.
• 08-19-2009
robwhit
here's another way
Code:

```int main() {     int (*a)[10] = new int[3][10];     a[1][5] = 10;     delete [] a;     return 0; }```