Homework 1: C/C++ Review
Due: Thursday, February 14, before 9:00 pm
Instructions: Your solutions to the following problems must be typed, converted to PDF, and submitted on Blackboard. It is okay to discuss concepts underlying the problems with other students, but all final solutions must be your own work.
All solutions must be typed, converted to PDF, and submitted on Blackboard. No other format is acceptable. Scans or photos of hand-written solutions will not be accepted.
Question 1: Pointers and Arrays
-
Trace the values of m, n, and *p
through lines 3 – 8 of the code; that is, show how each of
the variables changes through each line of the code. What is the
output?
1 int m = 5, n = 7 ; 2 int *p ; 3 p = &n ; 4 *p = 2 * n + m ; 5 *p = 2 * n + m ; 6 p = &m ; 7 *p = 2 * m + n ; 8 *p = 2 * m + n ; 9 cout << "m = " << m << ", " ; 10 cout << "n = " << n << ", " ; 11 cout << "*p = " << *p << endl ; -
Consider the following code fragment:
int x ; int *ptr = &x ; ptr++ ; If the variable x is stored at address 3173315904, what is the value of ptr after execution of the code fragment? -
Suppose I want to make an array of Graph objects using
the Graph class from Project 1. Why will the following
not work?
Graph *GArray = new Graph[100] ; -
What output does the following code fragment produce?
int arr[5] = {1,2,3,4,5} ; int *ptr = arr ; cout << *(ptr + 2) << endl ;
Question 2: Classes
Consider the following code fragment:
- Suppose leo is a Lion object. What syntax would I use to invoke the Eats() method on leo?
- Suppose lionPtr is a pointer to a Lion object. What syntax would I use to invoke the Sleep() method on the Lion object pointed to by lionPtr?
- Why is the private class variable called m_name and not simply name?
-
What output will the following code fragment produce?
Animal *leo = new Lion("Leo") ; leo->Eats() ;
Question 3: Iterators
The WideArray class implements a special array type for which each element consists of two 64-bit (long) quantities. That is, the first element of a WideArray is the first two elements of the underlying long array, the second element of the WideArray consists of the third and fourth words of the underlying array, etc.
- Why are waBegin and waEnd defined as members of the WideArray class rather than of the waIterator class?
- Write the implementation of operator++.
- Write the implementation of waEnd.
Question 4: Memory Errors
-
What is the likely results of running the following code fragment?
Why?
int *ptr = (int *) 0xfeedbeef ; *ptr = 0 ; -
Suppose a class uses a dynamically-allocated integer array,
pointed to by an int* variable named data. The
current capacity of the array is stored in the integer
variable capacity. The following code fragment is meant
to dyamically resize the array, doubling its capacity. What is
the major memory error and how would you detect it?
int *tmp = new int[2 * capacity] ; for (int i = 0; i < capacity; i++) { tmp[i] = data[i] ; } data = tmp ; capacity = 2 * capactiy ;