arrayscgccstructdevkitpro

Program freezes when setting values in an array using for loops, C Devkitpro 3DS


For a homebrew Minecraft-like clone for the 3DS, I'm attempting to create a data struct called a Chunk that contains a position, and a 3D array of ints, where an int in the array represents a block ID.

It is defined as so:

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;

In order to fill a Chunk, I have a function that takes a pointer to the variable. It is meant to fill the 'blocks' array with the block IDs it should contain.

However, this doesn't happen, and the program hangs on execution. The function is as so:

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
}

and is called like:

Chunk newChunk;
generate_chunk(&chunk);

What happens is whenever the array or any of its values are referenced hereafter, the program will hang.

Oddly, if I put the function calling behind an if statement, the program still freezes on the first frame despite it not being called at that moment.

Even more curiously, if I assign the values without for loops like this:

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
}

The program no longer hangs. It seems to fail whenever I try to assign values using a for loop. I'm probably missing something obvious, but it's driven me to think that this could even be a problem with the compiler (it probably isnt)

The compiler is GCC under DEVKITPRO.

Thanks!


Solution

  • Okay, it seems that the 3DS does not allow 3D arrays above around [19][19][19], when all sides are equal, though that may be flexible if you make the dimensions unequal.