How can i create an n-dimensional array in c

Posted by shortCircuit on Stack Overflow See other posts from Stack Overflow or by shortCircuit
Published on 2013-11-09T21:49:08Z Indexed on 2013/11/09 21:53 UTC
Read the original article Hit count: 203

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about c

    Related posts about pointers