1: //pointers4.cpp 3: #include <iostream> 4: using namespace std; 6: int main() 7: { 8: cout << "\nThis program illustrates the connection between pointers " 9: "and arrays\n(using static arrays) and also some \"pointer " 10: "arithmetic\"."; 11: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n'); 13: int a[] = { 11, 22, 33, 44, 55 }; 15: cout << "\nFirst we point at the first element of an array " 16: "in two different ways.\nThen we use the two different pointers " 17: "to display that same first element.\n"; 18: //THE NAME OF AN ARRAY IS ALSO A POINTER TO ITS FIRST ELEMENT: 19: int* p_int1 = a; 20: int* p_int2 = &a[0]; 21: cout << *p_int1 << endl; 22: cout << *p_int2 << endl; 23: cout << "Press Enter to continue ... "; cin.ignore(80, '\n'); 25: //POINTER ARITHMETIC IS "SMART" 26: cout << "\nNext we do some pointer arithmetic: We point at the " 27: "3rd element of the array,\nand use that pointer (unchanged) " 28: "to display the 3rd, 5th and first elements\nof the array.\n"; 29: int* p_int3 = &a[2]; //p_int3 points at the third element of a 30: cout << *p_int3 << endl; 31: cout << *(p_int3 + 2) << endl; //Display the fifth element of a 32: cout << *(p_int3 - 2) << endl; //Display the first element of a 33: cout << "Press Enter to continue ... "; cin.ignore(80, '\n'); 35: cout << "\nFinally, we do some more pointer arithmetic: We modify " 36: "the pointer pointing\nat the 3rd element of the array to point, " 37: "in turn, at the 4th, 5th, 4th and\n3rd elements of the array, " 38: "and after each modification use the modified\npointer to " 39: "display the value pointed at.\n"; 40: ++p_int3; //p_int3 now points at the fourth element of a 41: cout << *p_int3 << endl; 42: p_int3++; //p_int3 now points at the fifth element of a 43: cout << *p_int3 << endl; 44: --p_int3; //p_int3 now points at the fourth element of a 45: cout << *p_int3 << endl; 46: p_int3--; //p_int3 now points at the third element of a 47: cout << *p_int3 << endl; 48: cout << "Press Enter to continue ... "; cin.ignore(80, '\n'); 49: }