Me vs. Pointers : Round 5

Started by
1 comment, last by deathkrush 17 years, 8 months ago
Howdy! I have a question about my piece of code that i dont understand. Well, its a piece of code from my book altered by me. My questions will be within the code as comments. Thanks for any help.

#include <string>
#include <vector>
#include <iostream>

using namespace std;

string* GetItem(vector<string>* pWeapon, int num);

int main()
{
	vector<string> weapon;
	weapon.push_back("knife");
	weapon.push_back("mp5");
	weapon.push_back("armor");

	cout << "Sending a returned pointer to cout:\n"
		 << *GetItem(&weapon,0) << "\n\n"; // why do i have to put the * symbol infront of the function call?

	cout << "Assigning a returned pointer to a variable:\n";
	string item = *GetItem(&weapon,1);
	cout << item << "\n\n";
	
	cout << "Assigning a returned pointer to a pointer:\n";
	string* pItem = GetItem(&weapon,2);
	cout << *pItem << "\n\n";

	cout << "Changing the third item with a pointer:\n";
	*pItem = "Awp";
	cout << *pItem << "\n\n";

	return 0;
}

string* GetItem(vector<string>* pWeapon, int num)
{
	return &(*pWeapon)[num]; // why do i have to put the & in the return statement, along with the * symbol? what is this doing? I know its returning the value, but how are the symbols commanding this?
}

Advertisement
Quote:
// why do i have to put the * symbol infront of the function call?


Because the function returns a string pointer so you need to dereference the returned pointer to see the actual string value.

Quote:
// why do i have to put the & symbol in the return statement when i want to return the value of pWeapon?


You're not returning a value, you are returning a pointer. See first you dereference the vector pointer so you can get at its elements, (*pWeapon). Then you access element num, [num] and return a pointer to that element by adding & to the front of the statement.
Quote:Original post by NUCLEAR RABBIT
cout << "Sending a returned pointer to cout:\n"
<< *GetItem(&weapon,0) << "\n\n"; // why do i have to put the * symbol infront of the function call?
}

GetItem returns a pointer to std::string. If you print it out, you will se the memory address of the std::string. Since you want to print out the contents, you need to dereference the pointer with the * operator.
Quote:Original post by NUCLEAR RABBIT
string* GetItem(vector<string>* pWeapon, int num)
{
return &(*pWeapon)[num]; // why do i have to put the & symbol in the return statement when i want to return the value of pWeapon?
}

(*pWeapon)[num] returns an std::string, but the function GetItem must return a pointer to std::string. In order to return a pointer, you use the & operator to get the address of the std::string.
deathkrushPS3/Xbox360 Graphics Programmer, Mass Media.Completed Projects: Stuntman Ignition (PS3), Saints Row 2 (PS3), Darksiders(PS3, 360)

This topic is closed to new replies.

Advertisement