CPSC170A
Fundamentals of Computer Science II

Lab 19

Pointers

Trace Pointers

For each of the follwing, what will be printed when it is run. If it produces a compile or runtime error, just put error. If prints something, but it can’t be predicted, put unknown.

  1. int main() {
      int x = 1;
      int y = 2;
      std::cout << x << " " << y  << std::endl;
      std::cout << &x << " " << &y  << std::endl;
      return 0;
    }
  2. int main() {
      int x = 1;
      int y = 2;
      int* p1 = &x;
      int* p2 = &y;
      std::cout << p1 << " " << p2  << std::endl;
      std::cout << *p1 << " " << *p2  << std::endl;
      return 0;
    }
  3. int main() {
      int x = 1;
      int y = 2;
      int* p1 = &x;
      int* p2 = &y;
      x = 3;
      std::cout << *p1 << " " << *p2  << std::endl;
      return 0;
    }
  4. int main() {
      int x = 1;
      int y = 2;
      int* p1 = &x;
      int* p2 = &y;
      x = y;
      std::cout << *p1 << " " << *p2  << std::endl;
      y = 3;
      std::cout << *p1 << " " << *p2  << std::endl;
      return 0;
    }
  5. int main() {
      int x = 1;
      int y = 2;
      int* p1 = &x;
      int* p2 = &y;
      int z = 3;
      p1 = &z;
      std::cout << *p1 << " " << *p2  << std::endl;
      return 0;
    }
  6. int main() {
      int x = 1;
      int y = 2;
      int* p1 = &x;
      int* p2 = &y;
      p1 = p2;
      std::cout << *p1 << " " << *p2  << std::endl;
      int z = 3;
      p2 = &z;
      std::cout << *p1 << " " << *p2  << std::endl;
      return 0;
    }
  7. int main() {
      int x = 1;
      int y = 2;
      int* p1 = &x;
      int* p2 = &y;
      *p1 = 3;
      *p2 = *p1;
      std::cout << *p1 << " " << *p2  << std::endl;
      return 0;
    }
  8. struct Point {
      int x, y;
      int get_x() const;
      void print() const;
    }
    
    int Point::get_x() const {
      return x;
    }
    
    void Point::print() const {
      std::cout << this->x << std::endl;
    }
    
    int main() {
      Point pt = {1, 2};
      Point* pp = &pt;
      std::cout << *pp.get_x() << std::endl;
      std::cout << *(pp.get_x()) << std:endl;
      std::cout << (*pp).get_x() << std:endl;
      std::cout << pp->get_x() << std:endl;
      pp->print();
    }


Swap

Write the C++ function void swap(int* num1, int* num2) that swaps the referenced values of the two integer pointer parameters.