I am converting matlab code to C. Here I am stuck in the matlab reshape function. I am not quite getting the idea to implement in C.
So far I have written like this


Code:
int*** copy2dTo3D(int rows, int cols,int levels, int colsize,int **ar)
{
int i,j,k,x,y;
int*** array_3d;


array_3d = (int***)malloc(levels*sizeof(int **));
for (i = 0; i < levels; i++)
{
array_3d[i]=(int **)malloc(rows*sizeof(int *));
for (j = 0; j < rows; j++)
{
array_3d[i][j]=(int *)malloc(cols*sizeof(int));
for (k = 0; k < cols; k++)
{


                 if(j%2==0)
                 {
                 array_3d[i][j][k] = ar[j][x++];
                 printf("%d ",array_3d[i][j][k]);
                     if(x==colsize) x=0;
                    }
                    else
                    {
                     array_3d[i][j][k] = ar[j][y++];
                     printf("%d ",array_3d[i][j][k]);
                     if(y==colsize) y=0;
                    }
}
}
}
return array_3d;
}
but this is getting me segmentation fault. In matlab if you provide a 2D matrix and mention the size(row*col*levels) of new 3D matrix. It does. And while it does it makes in each level a row*col size matrix.
Most important thing while filling the new row*col matrix it takes data from 2D matrix like this:

twoD =


1 2 3 4 5 6
7 8 9 10 11 12
three3D = reshape(twoD, 2,2,3)
and result is like
three3D(:,:,1) =


1 2
7 8




three3D(:,:,2) =


3 4
9 10




three3D(:,:,3) =


5 6
11 12



any idea how to implement it in C? I am banging my head into wall literally for days.
Thanks in advance.