1: // Filename: PTR_EX1.CPP 2: // Purpose: Illustrates some simple integer pointers (pointers to int). 4: #include <iostream> 5: #include <iomanip> 6: using namespace std; 8: int main() 9: { 10: cout << "\nThis program illustrates integer pointers." 11: << "\nStudy the source code and the output simultaneously.\n\n"; 13: // Note the possible variations in the position of *. 14: // The first variation is the one we use. 15: int* iPtr1; 16: int *iPtr2; 17: int * iPtr3; 19: // Here are some "ordinary" initialized variables of type "int". 20: int i1 = 7; 21: int i2 = 10; 22: int i3 = -3; 24: // We can assign the address of an "ordinary" variable to a 25: // pointer variable, using the "address of" operator &, as in: 26: iPtr1 = &i1; 27: iPtr2 = &i2; 28: iPtr3 = &i3; 30: // Next we output some "values pointed to", i.e. the "referents" 31: // of some pointers, which we get by "dereferencing" the pointer 32: // variables, and we also output the values of the pointer variables 33: // themselves, just out of curiosity, and because we can. 34: cout << endl; 35: cout << setw(4) << i1 << setw(4) << *iPtr1 << " " << iPtr1 << endl; 36: cout << setw(4) << i2 << setw(4) << *iPtr2 << " " << iPtr2 << endl; 37: cout << setw(4) << i3 << setw(4) << *iPtr3 << " " << iPtr3 << endl; 38: cout << endl; 40: // Pointers can also be initialized at the time of declaration: 41: int i = 15; 42: int* iPtr = &i; 43: cout << setw(4) << i << setw(4) << *iPtr << endl; 44: cout << endl; 46: // Don't use declarations like this: 47: int* jPtr1, jPtr2; 48: // This suggests you have declared two "pointer to int" variables, 49: // when in fact you have only declared one (i.e. jPtr1). The second 50: // variable (jPtr2) is in fact just an ordinary int variable: 51: jPtr2 = 123; 52: jPtr1 = &jPtr2; 53: cout << setw(4) << jPtr2 << setw(4) << *jPtr1 << endl; 54: cout << endl; 56: return 0; 57: }