Pointer question

In the code below. I believe I am returning the memory location of the value I am looking for. How can get the value?

main.cpp
1
2
3
4
5
6
int choice = 0;
	PlayerMenu *newPM = new PlayerMenu;
	File *file = new File;
	
	// Menu for loading, creating or exiting the game
	choice =  newPM->menuChoices();


PlayerMenu.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int PlayerMenu::menuChoices() const
{
	int choice1 = 0;  // Initialize choice (temp var)

	while( choice1 != 3 )
	{
		cout << "Welcome to DarksVille RPG.  Please\n"
				<< "choose from the following: \n\n";
		cout << "1. Create a character\n"
				<< "2. Load a character\n"
				<< "3. Exit\n\n"
				<< "Choice: ";

		cin >> choice1;

		if( choice1 < 1 || choice1 > 3 ) { cout << "\nInvalide choice!\n\n"; }			// checking for valid choice
		if( choice1 == 1 || choice1 == 2 || choice1 == 3 ) { break; return choice1 ; }	// checking for proper choice
	}

}


I am not sure how to deference the value so I can get at the value instead of the memory location.

Sean
menuChoices() returns an int, and an int is what you get.

Have you tried printing to see if it is what you think it is?

Hope this helps.
Yes, it's printing out what is getting captured in the debug. Inside the function it still have the int "1" which is what I have been choosing. However, when it gets returned to the main loop it is printing out. 1380172400

from inside the function choice1 holds 1 and when it gets put into choice in "Int main" it gets changed to 1380172400

Last edited on
menuChoices is returning garbage.

look at line 17:

 
if( choice1 == 1 || choice1 == 2 || choice1 == 3 ) { break; return choice1 ; }


You are doing a break which exits the loop (ie: the return statement immediately following it does not get executed).

Therefore the program proceeds to end the function without hitting any return statement. Therefore you get junk.

Solution: remove the break;
Ok, I feel pretty stupid now. Thanks, that was it. I fixed the following line of code as follows.

if( choice1 == 1 || choice1 == 2 ) { return choice1; break; }

I also realized I didn't need to check for choice 3 because the loop automatically stops if the value of choice is = to 3. So I was able to condense it some. thanks for your help. I must have looked at that like 50 times and missed it.

Sean
Actually Disch told you to remove the break, not change its place. If function returns some value, it automatically stops, so you don't need to exit the loop by break. This instruction will never be reached.
Topic archived. No new replies allowed.