I have this D-code for reading data from a file:
int foo (SomeStruct[] somestruct_array)
{
// get file_handle...
for (uint i = 0; i < 1000; i++) {
file_handle.readf ("%e %e %e %e %e %e\n",
&(somestruct_array[i].pos_x), &(somestruct_array[i].pos_y),
&(somestruct_array[i].pos_z), &(somestruct_array[i].vel_x),
&(somestruct_array[i].vel_y), &(somestruct_array[i].vel_z));
}
return 0;
}
As you can see, the lines are getting quiet long and I keep repeating somestruct_array[i]. It’s not a big deal, but I tried to shorten that and write:
int foo (SomeStruct[] somestruct_array)
{
// get file_handle...
for (uint i = 0; i < 1000; i++) {
auto elem = somestruct_array[i];
file_handle.readf ("%e %e %e %e %e %e\n",
&(elem.pos_x), &(elem.pos_y),
&(elem.pos_z), &(elem.vel_x),
&(elem.vel_y), &(elem.vel_z));
}
return 0;
}
This results in all the element members being nan.
So: Is it possible to get a reference to array elements?
The problem is that
elemis a copy of the array element, so the pointers you pass toreadfare pointers to the temporary value.You have two options here, you can use a pointer:
or, you can iterate the array by reference:
Note that if the array is 1000 elements long, you can just write: