Source of pointers3.cpp


  1: //pointers3.cpp

  3: #include <iostream>
  4: #include <string>
  5: using namespace std;

  7: int main()
  8: {
  9:     cout << "\nThis program illustrates the dereferencing of "
 10:         "pointer variables.";
 11:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 13:     //Dereferencing a pointer variable to obtain the value pointed at
 14:     //Here the pointer is pointing at static storage
 15:     int i = 10;
 16:     i = i + 1;
 17:     cout << "\nCurrent value of i: " << i << endl;
 18:     cout << "1Press Enter to continue ... "; cin.ignore(80, '\n');

 20:     int* p_i = &i;
 21:     *p_i = *p_i + 1;
 22:     cout << "\nCurrent value of i: " << *p_i << endl;
 23:     cout << "2Press Enter to continue ... "; cin.ignore(80, '\n');

 25:     //Here the pointer is pointing at dynamic storage
 26:     int* p_int = new int;
 27:     *p_int = 17;
 28:     *p_int = *p_int + 5;
 29:     cout << "\nValue now pointed at by p_int: " << *p_int;
 30:     cout << "\n3Press Enter to continue ... "; cin.ignore(80, '\n');

 32:     struct ClubMember
 33:     {
 34:         string name;
 35:         int age;
 36:         double balance;
 37:     };

 39:     //Dereferencing a pointer variable pointing at a structured type
 40:     ClubMember* p_cm = new ClubMember;
 41:     p_cm->name = "John";
 42:     p_cm->age = 32;
 43:     p_cm->balance = 100.00;
 44:     cout << "\n" << (*p_cm).name << ", who is " << (*p_cm).age
 45:         << " years old, owes $" << (*p_cm).balance << ".";
 46:     cout << "\n4Press Enter to continue ... "; cin.ignore(80, '\n');

 48:     //The alternative to the previous line is ...
 49:     p_cm->name = "Alice";
 50:     p_cm->age = 27;
 51:     p_cm->balance = 55.95;
 52:     cout << "\n" << p_cm->name << ", who is " << p_cm->age
 53:         << " years old, owes $" << p_cm->balance << ".";
 54:     cout << "\n5Press Enter to continue ... "; cin.ignore(80, '\n');
 55: }