Constructing arrays of structs

Stephen Tashiro tashiro at zianet.com
Tue Jan 23 18:15:29 UTC 2024


If the constructor of a class needs to create an array of structs 
whose dimensions are inputs, what's the syntax for doing this?

For a non-example, the following program errors in main() because 
in t.array[][] "index [0] is out of bounds".


import std.stdio;

     struct Point
     {
      uint x;
      uint y;
      void printInfo()
      {
         printf("(%d $d )",x,y);
      }
     }


     class testClass
     {
       uint dimension;
       Point[][] array;

       this(uint the_dimension)
       {
         dimension = the_dimension;
         auto array = new Point[][](the_dimension,the_dimension);
         for(uint i = 0; i < dimension; i++)
         {
            for(uint j = 0; j < dimension; j++)
            {
               array[i][j].x = i;
               array[i][j].y = j;
            }
         }
       }
     }

     void main()
     {
        auto t = new testClass(5);

        for(uint i = 0; i < t.dimension; i++)
        {
           for(uint j = 0; j < t.dimension; j++)
           {
             printf("(%d %d)",t.array[i][j].x, t.array[i][j].y);
              //t.array[i][j].printInfo();
           }

        }

     }




More information about the Digitalmars-d-learn mailing list