【发布时间】:2021-10-13 04:15:00
【问题描述】:
对于 3DS 的类似 Minecraft 的自制克隆,我正在尝试创建一个名为 Chunk 的数据结构,其中包含一个位置和一个 3D 整数数组,其中数组中的一个整数代表一个块 ID。
是这样定义的:
typedef struct{
Vector3 position; //Vector3 is a struct that simply contains xyz as floats, similar to Unity
int blocks[16][128][16]; //Array of ints, each int represents a block ID
} Chunk;
为了填充一个块,我有一个函数,它接受一个指向变量的指针。它的目的是用它应该包含的块 ID 填充“块”数组。
但是,这并没有发生,程序在执行时挂起。 函数是这样的:
void generate_chunk(Chunk *chunk)
{
int newBlocks[16][128][16]; //Create temp 3D array
int x,y,z; //For loop coordinate values
for(x=0; x<16; x++) { //Loop X
for(z=0; z<16; z++) { // Loop Z
for(y=0; y<128; y++) { // Loop Y
//<enum> BLOCK_GOLD_ORE = 6, as a test
newBlocks[x][y][z]=(int)BLOCK_GOLD_ORE; //Set the value in the position xyz of the array to 6
}
}
}
/* The runtime then freezes/crashes whenever the array "newBlocks" is referenced. */
printf("\x1b[14;2Hgenerate_chunk :: %i", newBlocks[0][0][0]); //Debug print //!Crashes
//! vvv Uncomment when I've solved the problem above
//! memcpy(chunk->blocks, newBlocks, sizeof(chunk->blocks)); //Copy the temp array to the struct
}
并且被称为:
Chunk newChunk;
generate_chunk(&chunk);
只要以后引用数组或其任何值,程序就会挂起。
奇怪的是,如果我将函数调用放在 if 语句后面,程序仍然会在第一帧冻结,尽管当时它没有被调用。
更奇怪的是,如果我在没有这样的 for 循环的情况下分配值:
void generate_chunk(Chunk *chunk)
{
int newBlocks[16][128][16]; //Create temp 3D array
newBlocks[0][0][0]=(int)BLOCK_GOLD_ORE; //Set its first value to 6 (enum)
printf("\x1b[14;2Hgenerate_chunk :: %i", newBlocks[0][0][0]); //Debug print, doesnt crash anymore
}
程序不再挂起。每当我尝试使用 for 循环分配值时,它似乎都会失败。我可能遗漏了一些明显的东西,但这让我认为这甚至可能是编译器的问题(可能不是)
编译器是DEVKITPRO下的GCC。
谢谢!
【问题讨论】:
-
你确定程序在你认为的地方崩溃了吗?
printf调用不会刷新输出缓冲区。 -
@WeatherVane 我很确定。没有显示有任何内存错误,并且完全删除该函数的所有提及允许其他一切运行完全正常。并且仅删除
printf调用也可以使其正常运行,因为“newBlocks”不再在 for 循环之外被引用。 -
如果您
fflush(stdout),您将 100% 确定。 -
@WeatherVane 哦,对了,抱歉,现在刚试过,不幸的是它仍然在第一帧崩溃。
-
题外话:为什么不直接初始化
chunk->blocks,而不是初始化newBlocks,然后将memcpy写入chunk->blocks?
标签: arrays c gcc struct devkitpro