C - Convert array of elements into 2-d matrix

It might be a stupid question, but I wonder if there is a efficient way to do this.

The situation:

int* array = malloc(n * m * sizeof(int));
//want to convert array into M[n][m]

what I am doing now:

int** M = malloc(n * sizeof(int*));
for(int i = 0; i < n; i++, array += m)
  M[i] = array; 

I don't think the conversion should be this complex. Is there any simple syntax C provided? Can I declare an extern M[n][m] then set its address to the array?

(error handling and memory management in the sample is omitted for simplicity. Just think it as a part of some function.)

#c #arrays

4 Likes2.05 GEEK