gpt4 book ai didi

在c中将1d数据转换为3d的c代码

转载 作者:行者123 更新时间:2023-11-30 21:39:03 25 4
gpt4 key购买 nike

我有一个一维数组。

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

最佳答案

看来你的逻辑没问题。问题在于 1D 和 3D 数组的声明。

1) C 中没有 byte 数据类型

2) new 不是 C 的一部分。您不能使用 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;
}

关于在c中将1d数据转换为3d的c代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42477954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com