2017-02-27 28 views
-5

我在1D中有一個數組。用於將1d數據轉換爲3d的c代碼

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}; 

我需要用C此轉化爲形式的3D陣列:

data[3][3][3] 

有人可以幫助我這樣做呢?


我試了下面的代碼。似乎沒有工作:

#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; 
} 
+1

這不是C代碼。請描述你的問題比「不行」更好。究竟是什麼行爲?你有沒有使用調試器來通過代碼來試圖找出你可能做錯了什麼? – kaylum

+0

'byte [] [] [] res = new byte [3] [3] [3];'不應該編譯。它看起來像Java,而不是C或C++。你能顯示你的編譯和鏈接命令嗎?或者顯示嘗試編譯和鏈接的錯誤? – jww

回答

0

你的邏輯似乎沒問題。問題在於1D和3D陣列的聲明。

1)ID C中沒有數據類型爲byte

2)new是不使用new

嘗試爲您的代碼如下修改工作下的部分不能分配內存

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; 
} 
+0

感謝您的回答。它完美的工作。 – shashi

+0

我希望你能理解修改 –

+0

是的,我明白了。再次感謝。 – shashi