I have an array of pointers to some particle objects: Particle* particles[ TOTAL_PARTICLES ];
where TOTAL_PARTICLES = 10;
.
When I run this code below,
for( Particle* p : particles )
{
cout << "Attempting to create particle!\n";
p = new (nothrow) Particle( x, y );
cout << p << "\n";
if ( p == nullptr )
{
cout << "Error assigning memory!\n";
}
else
{
cout << "Particle created!\n";
}
}
for( Particle* p : particles )
{
cout << "Nullptr? " << ( p == nullptr ) << "\n";
}
this is the output:
Attempting to create particle!
0x2393c00
Particle created!
Attempting to create particle!
0x2393c20
Particle created!
Attempting to create particle!
0x2393c40
Particle created!
Attempting to create particle!
0x2393c60
Particle created!
Attempting to create particle!
0x2393c80
Particle created!
Attempting to create particle!
0x2393ca0
Particle created!
Attempting to create particle!
0x2393cc0
Particle created!
Attempting to create particle!
0x2393ce0
Particle created!
Attempting to create particle!
0x2393d00
Particle created!
Attempting to create particle!
0x2393d20
Particle created!
Nullptr? 0
Nullptr? 0
Nullptr? 0
Nullptr? 0
Nullptr? 1
Nullptr? 0
Nullptr? 1
Nullptr? 0
Nullptr? 1
Nullptr? 1
I don't understand why, even though the console tells me all particles were successfully created and have non-null pointers to them, when I iterate over them again, some of them suddenly become nullptr.
The most baffling thing is, this only happens if I use a range-based for loop. If I replace the first for( Particle* p : particles )
with for( int i = 0; i < TOTAL_PARTICLES; ++i )
and keep the second for loop as a ranged-based for loop, the code works as expected.
Does anyone have any ideas why the array of pointers to particles suddenly become nullptr? There's one more thing to note: I tried iterating over the array of pointers without actually creating any particles, and I received a similar output as well, which makes me suspect that somehow the code in the first ranged-based for loop isn't being "saved" somehow.
for( Particle* p : particles )
{
//...
p = new (nothrow) Particle( x, y );
//...
}
Note that p
is a Particle*
. This means that you are just copying the pointer out of the array, so the assignment will not change the array.
You could instead take a reference to the pointers:
for (Particle*& p : particles)
{
//...
}
Taking a reference to the pointer will mean that when you assign to p
, the pointer in the array will be updated.