CS210 Lab: Recursion - Pointer and Reference Review


These questions are designed to review:

Review Questions:

  1. Given the following piece of code, why aren't a and b exchanged after the call to exchange? (How could you modify the code?)
    void exchange(int, int);
    
    int main
    {
        int a=5,b=7;
       
        exchange(a,b);
    }
    
    void exchange (int x, int y)
    {
       int temp;
    
       temp = x;
       x = y;
       y = temp;
       return;
    } // end exchange
    		
  2. What is the difference between ClearPtr and ClearPtr2 in the following code? Will both pointer and pointer2 be set to 0 after the calls to ClearPtr and ClearPtr2. Why/Why not?
    #include <iostream>
    using namespace std;
    
    void ClearPtr(int *&p);
    void ClearPtr2(int *p2);
    
    int main()
    {
    	int x=5, x2=6;
    	int *pointer, *pointer2;
    
    	pointer = &x;
    	pointer2 = &x2;
    
    	cout << "x is: " << *pointer << endl;
    	cout << "pointer is holding address: " << pointer << endl;
    	cout << endl;
    	cout << "x2 is: " << *pointer2 << endl;
    	cout << "pointer2 is holding address: " << pointer2 << endl;
    	cout << endl;
    
    	ClearPtr(pointer);
    	ClearPtr2(pointer2);
    
    	cout << "\n***after calling Clear Pointer functions***\n" << endl;
    
    	cout << "pointer is holding address: " << pointer << endl;
    	if (pointer == 0)
    		cout << "pointer is NULL and should not be accessed\n" << endl;
    	else
    		cout << "pointer is pointing to value: " << *pointer << "\n" << endl;
    
    	cout << "pointer2 is holding address: " << pointer2 << endl;
    	if (pointer2 == 0)
    		cout << "pointer2 is NULL and should not be accessed\n" << endl;
    	else
    		cout << "pointer2 is pointing to value: " << *pointer2 << endl;
    
    
    	return 0;
    }
    
    void ClearPtr(int *& p)
    {
    	p=0;
    }
    
    void ClearPtr2(int *p2)
    {
    	p2=0;
    }