gcc would let you create multi-dimensional arrays like that, but it is extension:
1 2 3 4 5 6 7 8 9
#include <iostream>
int main()
{
int M = 6;
int N = 6;
int A[M][N];
int (* pA)[N] = newint[M][N];
}
With the pedantic option turned on the compiler will say:
main.cpp: In function 'int main()':
main.cpp:7:13: warning: ISO C++ forbids variable length array 'A'
main.cpp:7:13: warning: ISO C++ forbids variable length array 'A'
main.cpp:8:15: warning: ISO C++ forbids variable length array 'pA'
main.cpp:8:30: error: 'N' cannot appear in a constant-expression
main.cpp:7:13: warning: unused variable 'A'
main.cpp:8:15: warning: unused variable 'pA'
You could use vectors of vectors, although it is not the most efficient solution (since it stores pointer to and the size of each row vector behind the curtains):
#include <iostream>
#include <vector>
usingnamespace std;
int main()
{
int N = 10;
int M = 8;
vector< vector<int> > A(N, vector<int>(M));
//int* pA = new int[M*N];
for (int i = 0; i < N; ++i)
{
for (int j = 0; j < M; ++j)
{
A[i][j] =
//pA[i * M + j] =
i * M + j;
}
}
for (int i = 0; i < N; ++i)
{
for (int j = 0; j < M; ++j)
{
cout.width(3);
cout <<
A[i][j]
//pA[i * M + j]
<< ' ';
}
cout << endl;
}
//delete[] pA;
}
The commented lines show you how to use the dynamic memory allocation and custom address arithmetic instead. As dangerous as it is, this is arguably more efficient approach, both performance and memory-wise (but marginally so, especially for wider matrices).