How to simulate dynamically-sized arrays in C

In C and C++, array bounds must be constant expressions in the declaration of an array. In other words, you cannot write code like this:
int N;
double A[N][N];
For experimentation, it is desirable to allow the user to input the size of an array. This can be simulated in C by using a vector of vectors, and then accessing it just as one would a 2-d array. For example, to create a simulated NxN array, the following code can be used:
A = (double **) malloc (sizeof(double *) * N);
for (i = 0; i < N; i++)
  A[i] = (double *) malloc (sizeof(double) * N);
Now, one can simply make references to A[i][j]. It's NOT a 2-d array; rather, it's a vector of vectors. The expression A[i] is first evaluated; it is a pointer (A is a vector of pointers). The semantics of C state that A[i] is equivalent to *(A+i). In any case, A[i] is the address of the start of another vector. We now perform the same operation --- if we let x = A[i], then x[j] just means "get the element in the j'th position of the vector x".

You should draw a picture to make sure you understand what's going on.

The above method may not be ideal; the main reason why is that the vectors are not contiguous.
You can allocate contiguous memory with the following code.
 

tmp = (double *) malloc (sizeof(double ) * N * N);
A = (double **) malloc (sizeof(double *) * N);
for (i = 0; i < N; i++)
  A[i] = &tmp[i * N];