# 3-dimensional arrays

• April 14th, 2013, 02:59 PM
ted_kingdom
3-dimensional arrays
Hi. I receive unexpected outcome in my programm. Instead of geting all combinations of 0, 1, 2 (i.e. 000, 001, ..., 222) I get only 000 001 002 010 011 012. Can somebody tell me why?
The idea of the progarmm is to create a crystal lattice. Each atom of the lattice has 3 coordinates (x, y, z). That's why I create class Atom. Then I create 3-dim array of the type derived from class Atom. Now each element of the class will represent an atom. If somebody has an idea how to implement it in a more sophisticated way, I will appreciate it. Thanks in advance!
Code:

```#include <iostream>   using namespace std;   class Atom {     public:       float x, y, z; };   typedef class Atom AtomType;   int main () {     float a=1; // lattice parameter     int Lx=2, Ly=2, Lz=2; // number of translated lattices along each axis       AtomType ***Atom1; // 3-dimensional dynamic array for atom type 1       Atom1 = new AtomType** [Lx];       for (int i=0; i<Lx; i=i+a) // start of for loop     {         Atom1[i] = new AtomType* [Ly];     } // end of for loop     for (int i=0; i<Lx; i=i+a) // start of the outer for loop     {         for (int j=0; j<Ly; j=j+a)         {             Atom1[i][j] = new AtomType [Lz];         }     } // end of the outer for loop cout << "Atom1:" << endl;     for (int i=0; i<=Lx; i++) // start of the 3 nested for loops to populate atoms of type 1     {         for (int j=0; j<=Ly; j++)         {             for (int k=0; k<=Lz; k++)             {                 Atom1[i][j][k].x = i*a;                 Atom1[i][j][k].y = j*a;                 Atom1[i][j][k].z = k*a;                   cout << Atom1[i][j][k].x << "  " << Atom1[i][j][k].y << "  " << Atom1[i][j][k].z << endl;             }         }     } // end of the 3 nested for loops to populate atoms of type 1         for (int i=0; i<=Lx; i++) // start deleting array Atom1     {         for (int j=0; j<=Ly; j++)         {             delete[] Atom1[i][j];         }     }     for (int i=0; i<=Lx; i++)     {         delete[] Atom1[i];     }     delete[] Atom1; // end of deleting array Atom1         return 0; }```
• April 14th, 2013, 03:37 PM
2kaud
Re: 3-dimensional arrays
Code:

```for (int i=0; i<=Lx; i++) // start of the 3 nested for loops to populate atoms of type 1     {         for (int j=0; j<=Ly; j++)         {             for (int k=0; k<=Lz; k++)```
Array subscripts start at 0 and end at one less than the number of elements in that dimension. So the loops should start at 0 and terminate when i < Lx etc. You have the same problem when you are deleting the array. When I tried your code I got an exception.
• April 14th, 2013, 03:59 PM
ted_kingdom
Re: 3-dimensional arrays
Thank you very much. You are absolutely right.