shashi shashi -4 years ago 68
C Question

c code for converting a 1d data into 3d in c

I have an array in 1D.

data[27]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27};

I need to convert this into a 3D array of the form:
data[3][3][3]
using C. Can someone help me doing this?

I tried the following code. Not seems to be working:



#include <stdio.h>

int main()
{

int x;
int y;
int z;
int res;
int data;
int byte[] data={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27}; // Read 4096 bytes
byte[][][] res = new byte[3][3][3];
for (x = 0 ; x != 3 ; x++) {
for (y = 0 ; y != 3 ; y++) {
for (z = 0 ; z != 3 ; z++) {
res[x][y][z] = data[3*3*x + 3*y + z];
}
}
}
printf("Printing the 3D matrix\n");
for (x = 0 ; x != 16 ; x++) {
for (y = 0 ; y != 16 ; y++) {
for (z = 0 ; z != 16 ; z++) {
printf("%d\t",res[x][y][z]);
printf("\n");
}
}
}


return 0;
}




Answer Source

Your logic seems to be okay. The problem is with the declaration of the 1D and 3D arrays.

1) There id no datatype as byte in C

2) new is not a part of C. You cannot allocate memory using new

Try the following changes for your code to work

int main()
{

int x;
int y;
int z;
int data[] ={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27}; // Read 4096 bytes
int res[3][3][3];
for (x = 0 ; x < 3 ; x++) {
    for (y = 0 ; y < 3 ; y++) {
        for (z = 0 ; z < 3 ; z++) {
            res[x][y][z] = data[3*3*x + 3*y + z];
        }
    }
}
printf("Printing the 3D matrix\n");
//run the loop till maximum value of x, y & z
for (x = 0 ; x < 3 ; x++) {
    for (y = 0 ; y < 3 ; y++) {
        for (z = 0 ; z < 3 ; z++) {
            printf("%d\t",res[x][y][z]);
            printf("\n");
        } 
    }
}
return 0;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download