How can i create an n-dimensional array in c
- by shortCircuit
I was thinking of making a function that would accept the size of array as a parameter and create a n dimensional array. My room-mate took the liberty of making it complex. He said lets write a function that takes n parameters and returns an n-dimensional array using those parameters as the dimensions. Now i realize an one-day and d array is easy to implement with pointers. For 2d array the snippet would be something like (standard way) :
int** x;
int* temp;
x = (int**)malloc(m * sizeof(int*));
temp = (int*)malloc(m*n * sizeof(int));
for (int i = 0; i < m; i++) {
x[i] = temp + (i * n);
}
where the array is of size m*n; But the problem lies how do we find the nested loop parameters for a n-dimensional array? Is there any way to optimize the code?