bordeo bordeo - 3 months ago 13
C++ Question

Array Pointer not returning from C++ function

I have the following code to initialize an array, which works:

int main() {
int particle_count = 10000;

MyRNG my_rng = MyRNG(0.0,1.0);

Particle simulation_particles[particle_count];
for (int i = 0; i < particle_count; i++)
{
for (int j = 0; j < 3; j++)
{
simulation_particles[i].assign(j,my_rng.next());
}
}


However, when I try to put the for loops in functions, all particles get set to the same values:

void initialize_particle(Particle * p,MyRNG rgen)
{
for (int i = 0; i < 3; i++)
{
float value = rgen.next();
p->assign(i,value);
}
}
void initialize_simulation_particles(int size,Particle * simulation_particles,MyRNG rgen)
{
for (int i = 0; i < size; i++)
{
initialize_particle(&simulation_particles[i],rgen);
}
}


int main() {
int particle_count = 10000;

MyRNG my_rng = MyRNG(0.0,1.0);

Particle simulation_particles[particle_count];
initialize_simulation_particles(particle_count,simulation_particles,my_rng);

nwp nwp
Answer

In void initialize_simulation_particles(int size,Particle * simulation_particles, MyRNG rgen) you take rgen by value. That means you get a copy of the random generator my_rng from main. Since it is a pseudo random number generator that produces the same numbers on a given state and you copy the same state to the function every time it produces the same number every time. The solution is to pass it by reference in initialize_simulation_particles and initialize_particle using MyRNG &rgen so that the state of my_rng progresses and therefore produces different numbers for each particle.