< Previous | Contents | Next >

Introducing the Pointing Program

The Pointing program demonstrates the mechanics of pointers. The program creates a variable for a score and then creates a pointer to store the address of that variable. The program shows that you can change the value of a variable directly, and the pointer will reflect the change. It also shows that you can change the value of a variable through a pointer. It then demonstrates that you can change a pointer to point to another variable entirely. Finally, the program shows that pointers can work just as easily with objects. Figure 7.1 illustrates the results of the program.

You can download the code for this program from the Course Technology website (www.courseptr.com/downloads). The program is in the Chapter 7 folder; the filename is pointing.cpp.


image

Figure 7.1

The pointer pScore first points to the variable score and then to the variable newScore, while the pointer pStr points to the variable str.

Understanding Pointer Basics 225



// Pointing

// Demonstrates using pointers


#include <iostream> #include <string>

using namespace std; int main()

{

int* pAPointer; //declare a pointer

int* pScore = 0; //declare and initialize a pointer int score = 1000;

pScore = &score; //assign pointer pScore address of variable score


cout << "Assigning &score to pScore\n";

cout << "&score is: " << &score << "\n"; //address of score variable cout << "pScore is: " << pScore << "\n"; //address stored in pointer cout << "score is: " << score << "\n";

cout << "*pScore is: " << *pScore << "\n\n"; //value pointed to by pointer


cout << "Adding 500 to score\n"; score += 500;

cout << "score is: " << score << "\n";

cout << "*pScore is: " << *pScore << "\n\n";


cout << "Adding 500 to *pScore\n";

*pScore += 500;

cout << "score is: " << score << "\n";

cout << "*pScore is: " << *pScore << "\n\n";


cout << "Assigning &newScore to pScore\n"; int newScore = 5000;

pScore = &newScore;

cout << "&newScore is: " << &newScore << "\n"; cout << "pScore is: " << pScore << "\n";

cout << "newScore is: " << newScore << "\n"; cout << "*pScore is: " << *pScore << "\n\n";

226 Chapter 7 n Pointers: Tic-Tac-Toe 2.0


cout << "Assigning &str to pStr\n"; string str = "score";

string* pStr = &str; //pointer to string object cout << "str is: " << str << "\n";

cout << "*pStr is: " << *pStr << "\n";

cout << "(*pStr).size() is: " << (*pStr).size() << "\n"; cout << "pStr->size() is: " << pStr->size() << "\n";


return 0;

}