There is something I still don't quite understand about the way matrices and other multidimensional arrays are represented in C and C+ and how to allocate them dynamically.
Consider the following code segment:
int main()
{
int n;
cin >> n;
int a[n][n];
...
}
If I understand correctly, this allocates an n by n matrix of integers on the stack. The (i,j)-th element of the matrix can be accessed using a[i][j]. The compiler automatically converts this into an access into the (n*i+j)-th element of a one dimensional array actually allocated.
Suppose now that I would like to allocate the n by n matrix a on the heap, instead of the stack. I can then do the following:
int main()
{
int n;
cin >> n;
int** a;
a = new int*[n];
for (int i=0;i<n;i++) a[i] = new int[n];
...
}
I can now access the (i,j)-th element again as a[i][j]. However, this is not exactly equivalent to the situation above as I actually had to allocate space for n*n int's, plus n pointers to int. Also, accessing a[i][j] now entails two accesses to memory instead of just one. On the other hand, the index computation n*i+j is avoided.
Suppose now that I am interested in n by m matrices where m is small, e.g., m=2. Using the array of row pointers then wastes 33% of the space. Is there any way of avoiding that?
I can of course allocate a one-dimensional array and do the index arithmetic myself, but this does not seem to be the best solution to me.
Any information would be appreciated!