# Thread: Using variables for array dimensions

1. ## Using variables for array dimensions

I have been away from c++ programming, and decided to start out by making a program that:

a) Accepts input to create a matrix (in form of an array)

b) Puts the matrix in row-echelon form

c) Solves the matrix using backwards substitution

Here is the code with errors when initializing the array:
Code:
```#include <iostream.h>

int main()
{
int width = 1;
int height = 1;

cout<<"Enter the number of columns in the augmented matrix: ";
cin>>height;

width = height + 1;

int matrix[width][height];

return 0;
}```

2. You are gonna need to allocate yourself some memory on the heap.

Code:
```int **matrix = new int *[width];
for (int i = 0; i < width; i++)
{
matrix [i] = new int [height];
}```
And then to clear up after yourself,

Code:
```for (int j = 0; j < width; j++)
{
delete [] matrix [j];
}
delete [] matrix;```

3. Ok, the code is very easy to implement, but I'm not sure how it is working / what it is doing. Could you explain a bit for me?

4. Basically, if you want to allocate an array like in your first example, the compiler must know how much memory to reserve for the array at compile time. This is obviously impossible as the array size depends on the user input. So we have to use what is known as dynamic allocation. This allows us to grab hold of a chunk of memory of any size (provided there enough in the machine) at any point whilst the program is running. This is what the 'new' operator does for us.

So,

int **matrix = new int *[width];

gives us a pointer to an array of pointers to integers (the first column or the backbone if you like). We then set each of those pointers to point to the first element of an array of integers (the rows),

for (int i = 0; i < width; i++)
{
matrix [i] = new int [height];
}

and voila. We now have a two dimensional array of whatever size we like. If you don't understand the whole pointers thing then I suggest reading up about it.

Once you have finished using the memory you requested with the 'new' operator you must give it back to the OS. In the opposite way as before, you give back all the memory by using,

for (int j = 0; j < width; j++)
{
delete [] matrix [j];
}
delete [] matrix;

The loop gives back all the memory contained in the rows and now we must return the backbone (first column). That's done by the bit after the loop.

Hope this helps