Source of ptr_ex3.cpp


  1: // Filename: PTR_EX3.CPP
  2: // Purpose:  Illustrates the connection between pointers and arrays.

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

  7: int main()
  8: {
  9:     cout << "\nThis program illustrates pointers with arrays."
 10:          << "\nStudy the source code and the output simultaneously.\n\n";

 12:     int count[5] = { 2, 5, 9, 12, 20 };
 13:     double real[4] = { -1.2, 3.5, 6.3, 9.1 };


 16:     int* iPtr;
 17:     iPtr = count;  // Equivalent to:  iPtr = &count[0];
 18:     cout << endl;
 19:     for (int i = 0; i < 5; i++)
 20:     {
 21:         cout << *iPtr << " ";
 22:         iPtr++;
 23:     }
 24:     cout << endl;


 27:     // Initialize dPtr to point at last array element:
 28:     double* dPtr = &real[3];

 30:     // Print out array values in reverse order:
 31:     for (int j = 3; j >= 0; j--)
 32:     {
 33:         cout << *dPtr << " ";
 34:         dPtr--;
 35:     }
 36:     cout << endl;

 38:     // Illustrate some additional "pointer arithmetic":
 39:     iPtr = &count[2];
 40:     cout << *(iPtr + 2) << endl;
 41:     cout << *(iPtr - 1) << endl;
 42:     iPtr -= 2;
 43:     cout << *iPtr       << endl;

 45:     return 0;
 46: }