CSE2050 Fall 2003 Exam #2, open book, open notes. Name ___________________ 1. For each statement, circle OK if there is no error, C if there is a compiler error, R if there is a run-time error message or exception, or U for undefined behavior (program might crash). (3 pts each). int *p = 0; OK (p is a NULL pointer) cout << *p << endl; U (print contents of address 0, segmentation fault) p = new int[10]; OK (creates array p[0]...p[9]) int *q = p + 3; OK (q = &p[3], q points to p[3]) cout << p - q << endl; OK (prints -3) p[10] = 0; U (index out of bounds) q[-1] = 1; OK (same as p[2] = 1;) q = 4; C (type mismatch, int* = int) sort(p, q); OK (sorts first 3 elements of p) delete p; U (should be delete[] p;) 2. Write a templated function size() which takes a pointer to a Node pointing to the root of a binary tree, and returning (as an int) the number of nodes in the tree. Node is defined as follows (30 pts). template struct Node { T data; Node *left, *right; }; // ANSWER (equivalent code is acceptable, but it should be // a non-member, a template function, and the parameter must be // type Node*. Don't forget to check if it's 0 (or NULL). template int size(Node* root) { if (root) return size(root->left) + size(root->right) + 1; else // root == 0 return 0; } 3. Complete the class below by writing the three member functions required by the rule of 3 (40 pts). class Complex { double *p; // 2 element array contains real and imaginary parts public: Complex(double r=0, double i=0): p(new double[2]) {p[0]=r; p[1]=i;} double real() const {return p[0];} double imag() const {return p[1];} // ANSWER (equivalent code is acceptable) ~Complex() {delete[] p;} // destructor Complex(const Complex& c): p(new double[2]) { // Copy constructor p[0] = c.real(); // or p[0] = c.p[0]; or copy(c.p, c.p+2, p); p[1] = c.imag(); } Complex& operator = (const Complex& c) { // Assignment operator p[0] = c.real(); p[1] = c.imag(); return *this; } };