Constructing arrays of structs
Renato
renato at athaydes.com
Tue Jan 23 18:23:22 UTC 2024
On Tuesday, 23 January 2024 at 18:15:29 UTC, Stephen Tashiro
wrote:
> 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();
> }
>
> }
>
> }
This works , your mistake was to not actually assign the array to
the class' field!
Change this line:
```d
auto array = new Point[][](the_dimension,the_dimension);
```
To this:
```d
this.array = new Point[][](the_dimension,the_dimension);
```
More information about the Digitalmars-d-learn
mailing list