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.
int main() { int x = 1; int y = 2; std::cout << x << " " << y << std::endl; std::cout << &x << " " << &y << std::endl; return 0; }
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; }
int main() { int x = 1; int y = 2; int* p1 = &x; int* p2 = &y; x = 3; std::cout << *p1 << " " << *p2 << std::endl; return 0; }
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; }
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; }
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; }
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; }
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.