# Thread: Two dimensional dynamically allocated array problem

1. ## 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;
}

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. 2. Ok problem solved. I had a different variable in for 'size' in the first for loop. Only saw it when posting up here. 3. 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 = new int[rows * cols];
for( int k = 1; k < rows; k++ ) {
myArray[k] = myArray + (k * cols);
}

// use myArray

delete [] myArray;
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. 4. Interesting, it's been a long time since I've messed around with dynamic arrays and the likes. Cheers for the input. 5. There's an even easier way. Use vector. Unless you're learning, there isn't much reason to use a dynamic array in C++. 6. here's another way
Code:
```int main() {
int (*a) = new int;
a = 10;
delete [] a;
return 0;
}``` Popular pages Recent additions 