C ++ 3d arrays

I am trying to run a 3D array, but the code just crashes in windows when I run it, here is my code;

#include <iostream>

using namespace std;

int main(){

    int myArray[10][10][10];

    for (int i = 0; i <= 9; ++i){
        for (int t = 0; t <=9; ++t){            
            for (int x = 0; x <= 9; ++t){

                myArray[i][t][x] = i+t+x; 

            }

        }

     }


    for (int i = 0; i <= 9; ++i){
        for (int t = 0; t <=9; ++t){
            for (int x = 0; x <= 9; ++t){

                cout << myArray[i][t][x] << endl;

            }

        }

    }

    system("pause");

}

      

can someone throw me a quick fix / explanation

0


source to share


2 answers


You have the line twice

for (int x = 0; x <= 9; ++t){

      

when do you mean



for (int x = 0; x <= 9; ++x){

      

A classic copy and paste error.

By the way, if you run this in the debugger and look at the values โ€‹โ€‹of the variables, it's pretty easy to see what's going on.

+14


source


David's answer is correct.

By the way, the convention is to use i, j and k for nested iterator indices, and also to use <array_length rather than <= array_length -1 as a terminator.

If you do this, you can make the size of the array constant and get rid of some magic numbers.



Also, a statement where you are using array indices could indicate an error.

The result might look like this:

const std::size_t ARRAY_SIZE = 10;

int myArray[ARRAY_SIZE][ARRAY_SIZE][ARRAY_SIZE];

for (std::size_t i = 0; i < ARRAY_SIZE; ++i) 
{
    for (std::size_t j = 0; j < ARRAY_SIZE; ++j)
    {
        for (std::size_t k = 0; k < ARRAY_SIZE; ++k)
        {
            std::assert (i < ARRAY_SIZE && j < ARRAY_SIZE && k < ARRAY_SIZE);
            // Do stuff
        }
    }
}

      

+2


source







All Articles