Pointer question

Started by
3 comments, last by Kotorez 11 years ago
Hello,

I am writing my first dungeon crawl game and I stumbled upon strange program behavior.

http://pastebin.com/ZVvmVdbf


    Board_level board;
    PlayerOn_Board player(0,0);
    board.setValues(20,20);
    //player.setPosition(10, 15);
    cout << player.returnX() << " " << player.returnY() << endl;

When I do "board.setValues(20,20)", player.returnX() and player.returnY() return 20s. I am expecting them both to be equal to zero since I declare them as zero and dont do any assigning. For some reason board object overwrites my player object. Can somebody please explain to my why it happens. I spent couple of hours trying to understand this.

Thanks
Advertisement

The two pointer members of the PlayerOn_Board class points to the local parameter variables in the constructor. As soon as the constructor returns, the pointers are no longer valid and your program is ill defined. The fact that it prints 20 and 20 is just an accident, but can likely be explained that, at the time you ask for the values, the values at the stack memory the pointers point to have been replaced by the parameters to the last function call.

What Brother Bob says.

PlayerOn_Board::PlayerOn_Board(int initX, int initY){                           
    playerX = &initX;
    playerY = &initY;
}

I am not sure why playerX and playerY are pointers. If you don't have a good reason, they shouldn't be. If you have a good reason, explain what it is and we can suggest alternatives.

Well basically what I wanted to do is to use all of the concepts I have learned and put them into one program including references/pointers. In this case the reason why I wanted to use pointers(probably a bad one) so when the player does a move I can just incriment the number by calling setPosition from the main() for example: if user presses UP do player.setPosition(10, 15), UP again player.setPosition(10, 16), RIGHT player.setPosition(11, 16) etc. By puting this values into setPosition, I though it would be easier for my PlayerOn_Board class to talk to Board_level through PlayerOn_Board::drawPlayer_board function.

Thanks a lot guys I fixed it. Usage of pointers in that situation was absolutely unnecessary. smile.png

This topic is closed to new replies.

Advertisement