I dont know how to use a for loop anymore?

I had this problem while programming physx, it must be something obvious since i am kind of new to c++. Hope the you guys can give me a light here

This class NxShapeDesc receive information of a shape such as its position, so i wanted to create an array of those to put all together later on. so i did this:
1
2
3
4
5
6
NxShapeDesc** shapeDescs = new NxShapeDesc*[4];
for(int i = 0 ; i < 4 ; i++)
	{
                //NewCubeShape first argument is the shape position
		shapeDescs[i] = &NewCubeShape(i,1,0);
	}


However, this piece of code gives me an array with all the shapes having the same position of the last shape(that would be 4)

So i was puzzled and tried this:

1
2
3
4
5
NxShapeDesc** shapeDescs = new NxShapeDesc*[4];
shapeDescs[0] = &NewCubeShape(0,1,0);
shapeDescs[1] = &NewCubeShape(1,1,0);
shapeDescs[2] = &NewCubeShape(2,1,0);
shapeDescs[3] = &NewCubeShape(3,1,0);


and it worked, my problem is solved but i want to know what happened here.

thank you guys
Last edited on
The two sets of statements are equivalent.
The for does what you'd expect it to, so that's not the problem. The problem, I believe, is that the function is returning a temporal copy of which you're taking the pointer. As its number suggests, the copy is temporal, so your pointers are invalid. My guess is that inside the loop the temporal objects are all allocated at the same address, so all your pointers are pointing to the same location. This doesn't happen when you unwind the loop (for some reason).

Next time you get a similar behavior, where all your objects have the same value even though the were initialized differently, check that the pointers point to different locations.
Topic archived. No new replies allowed.