tags:

views:

819

answers:

2

I'm trying to run a 3d array but the code just crashes in windows when i run it, here's 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

+14  A: 

You twice have the line

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

when you mean

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

Classic copy-and-paste error.

BTW, if you run this in a debugger and look at the values of the variables, it's pretty easy to see what's going on.

David Norman
pick this answer and be done with it.
Tim
You could equally well have found the same thing by including the "cout <<" line in your first nested loop as well.
CodeSlave
dammit, didn't see that, thanks :)
It's called 'classic copy-and-paste error' for a reason. We've all done it. :-)
David Norman
+2  A: 

David's answer is correct.

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

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

Also, an assertion at the point where you use the array indices might have pointed you to the error.

The result may look like:

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
        }
    }
}
JohnMcG
I prefer to write one condition per assert, to make it clearer *which* condition failed.
ChrisN
also, there is no "std::assert", assert is a macro (i wish you can namespace macros...)
Evan Teran
I'd also say (though not really important) to put i++ as opposed to ++i. Just looks neater. IMHO
baash05
also (just a little thingy), you've forgotten a semicolon after the array definition :)
Johannes Schaub - litb
It's actually better to be in the habit of doing ++i because increment-and-fetch is a less expensive operation than fetch-and-increment, although the compiler will typically optimize it away.
JohnMcG