// FILE: pointer.cpp // PURPOSE: Use pointer variables //--------------------------------------------------------------------- // COMPILATION INSTRUCTIONS: g++ and gxx // COMMAND LINE: g++ (or gxx) pointerS.cpp //============================================================= // INSTRUCTIONS: // 1. In intDriver: // 1. Examine how * (dereference) and & (address of) operators // work by running the program // 2. Complete the short programming problems therein // 2. Complete swap started below as specified. //================================================================= #include #include #include void swapDriver(void); void cls(void); void wait(void); void intPointers(void) { string title("Using pointers to ints"); cls(); cout << setw(40+title.length()/2) << title.c_str() << "\n\n"; int x(17), *px = &x; cout << "AFTER STATEMENT " << "int x(17), *px = &x;" << endl; cout << "x = " << x << endl; cout << "*px = " << *px << "\t* is the dereference operator\n"; cout << "px = " << px << "\tpx contains address of x\n"; cout << "&x = " << &x << "\t& is the address of operator\n\n"; //---------------------------------------------------------- // 1. Using px INSEAD OF x, assign -77 to x's memory location // YOUR CODE: //---------------------------------------------------------- // 2. Using px INSEAD OF x, add 5 to value at x's memory location // YOUR CODE: } void swap(int *p, int *q) { // postcondition: ints to which p and q are pointing are swapped } int main() { intPointers(); wait(); swapDriver(); wait(); int a(0), b(4), c(10); // (a = b ) = c = 7; a = (b = c) = 7; cout << "a = " << a << "\tb = " << b << "\tc = " << c << endl; wait(); cout << endl; return 0; } // main() void swapDriver(void) { string title("Testing swap function using pointers"); cls(); cout << setw(40+title.length()/2) << title.c_str() << "\n\n"; cout << "swap function prototype: void swap(int *p, int *q);\n"; int x(5), y(2); cout << "BEFORE call to swap(x, y): x = " << x << "\ty = " << y << endl; swap(&x, &y); cout << "AFTER call to swap(x, y): x = " << x << "\ty = " << y << endl; } void cls(void) { cout << string(55, '\n'); } void wait (void) { cout << "\nPress ..."; cin.ignore(10, '\n'); }