You can allocate an array of size n*n, and do extra arithmetic (which you can encapsulate in macros or classes) to access its elements:
Code: Select all
int *matrix = new int[n*n];
#define MATRIX(i, j) matrix[(i)*n + (j)]
MATRIX(2, 3) = 42;
cout << MATRIX(2, 3) << endl;
delete[] matrix;
Or allocate an array of int*, and initialize each member with a pointer to another allocated array:
Code: Select all
int *matrix = new int*[n];
for (int i = 0; i < n; i++) matrix[i] = new int[n];
...
matrix[2][3] = 42;
...
for (int i = 0; i < n; i++) delete[] matrix[i];
delete[] matrix;
And with STL this solution is even shorter:
Code: Select all
vector<vector<int> > matrix(n, vector<int>(n, 0));
matrix[2][3] = 42;
cout << matrix[2][3] << endl;
...