Works outside of the loop, not within
I don't even know what to search under to find the answer to this one...
For pointer practice, I'm making a mancala game. To test the classes I made, I'm trying to create a game board and set it up before I get to making the game itself.
I create two kinds of "buckets", end and middle. There are two ends, the rest of the board are middle buckets. (the only difference is that middle buckets start with some stones in them.)
Each bucket has a member (a pointer) that points to the next bucket down the line. the Bucket::link(Bucket) function sets the pointer to the address of the Bucket passed to it.
When setting up the board, I push end onto the vector. Then I add the rest onto the vector in a loop:
If I use the code in blue instead of green, only buckets and the last half (8-13) of the buckets link correctly. The first half are linked all over the place (later in the setup function it prints the address of each bucket and the address pointed to by a member of each bucket.)
for (int fill = 1; fill != totalBuckets; ++fill)
if (fill == (totalBuckets \ 2)
buckets[fill].link( buckets[fill - 1] );
for (int linker = 1; linker != totalBuckets; ++linker)
buckets[linker].link( buckets[linker - 1] );
buckets.link( buckets[buckets.size() - 1] )
If I use the green code instead of the blue, everything links up correctly. It looks like it's doing the same thing to me, but clearly that's not the case. I can also replace totalBuckets with buckets.size() and everything still works.
As I said, to me, it seems that the green and blue statements are identical, one is done each time through the loop as the vector is being created, and the other is done after the vector is full. I know that vectors don't behave quite the way I usually expect them to, but I don't think that adding a member changes the other members, so I really have no clue what's going on here.
On one hand, hey - it works now! However, I'd really like to know why.