## Tuesday, July 20, 2010

### 2D Arrays in C++ using New

In a previous post I discussed how to create 2D arrays in C. Here's the version for C++. Pointers can be easily used to create a 2D array in C++ using the operator "new" . The idea is to first create a one dimensional array of pointers, and then, for each array entry, create another one dimensional array. Here's a sample code:
```double** theArray = new double* [arraySizeX];
for (int i = 0; i < arraySizeX; i++)
// allocated arraySizeY elements for row i
theArray[i] = new double [arraySizeY];```
Voila!

To follow my previous post on 2D arrays in C, create a function called Make2DDoubleArray that returns a (double**) and then use it in the code to declare 2D arrays here and there
```double** Make2DDoubleArray(int arraySizeX, int arraySizeY) {
double** theArray = new double* [arraySizeX];
for (int i = 0; i < arraySizeX; i++)
theArray[i] = new double [arraySizeY];
return theArray;
}
```
Then, inside the code, i would use something like
`double** myArray = Make2DDoubleArray(nx, ny);`
Voila!

Of course, do not forget to remove your arrays from memory once you're done using them. To do this
```// first delete inner entries
for (i = 0; i < nx; i++) delete[] myArray[i];
delete[] myArray;
```

Cite as:
Saad, T. "2D Arrays in C++ using New". Weblog entry from Please Make A Note. http://pleasemakeanote.blogspot.com/2010/07/2d-arrays-in-c-using-new.html

#### 1 comment:

1. any idea on how to output a two dimensional array to the screen?