CSCI 159: exam practice sample solutions
Question 1: Basic pointers
For each of the cout statements below, show the values of x and y
and explain why they have those values.
int x, y;
y = 32;
x = 5;
int *ptr1;
int *ptr2;
ptr1 = &x;
(*ptr1) = 10;
x++;
cout << x << "," << y << endl;
ptr2 = ptr1;
ptr1 = &y;
y = 45;
cout << x << "," << y << endl;
(*ptr1) = 99;
(*ptr2) = (*ptr1) - 5;
cout << x << "," << y << endl;
Sample answer:
// here I'm showing the explanation as comments beside the lines of code
ptr1 = &x; // ptr1 now points to x
(*ptr1) = 10; // put 10 in x through ptr1
x++; // x now 11
cout << x << "," << y << endl; // 11,32 (y hasn't changed yet)
ptr2 = ptr1; // both ptrs now point to x
ptr1 = &y; // ptr1 now points to y (ptr2 still points to x)
y = 45; // y now 45
cout << x << "," << y << endl; // 11,45 (x hasn't changed since last cout)
(*ptr1) = 99; // change y to 99 through ptr1
(*ptr2) = (*ptr1) - 5; // change x to 99-5, i.e. 94, through ptr2
cout << x << "," << y << endl; // 94,99
Question 2: Arrays, new and delete[]
Write a main routine that does the following in the sequence shown:
- gets an integer size from the user (no error checking required),
- allocates one array of doubles of
that size and one array of ints of that size (using new for each of the allocations),
- fills the array of ints with values the user supplies (again no error checking required),
- fills the array of doubles with the square roots of the corresponding ints
(e.g. if our arrays were mydoubles and myints then mydoubles[i] gets the square root of myints[i]),
- deletes the array of ints,
- prints the elements from the array of doubles,
- deletes the array of doubles
Sample answer:
int main()
{
// get the size
int size;
cout << "Enter the array size";
cin >> size;
// allocate the arrays
int *myints = new(std::nothrow) int[size];
double *mydoubles = new(std::nothrow) double[size];
// note: really I should also have specified checks for nullptr here
// fill the int array
for (int i = 0; i < size; i++) {
cout << "Enter an integer";
cin >> myints[i];
}
// fill the doubles array
for (int i = 0; i < size; i++) {
mydoubles[i] = sqrt(myints[i]);
}
// delete the ints array
delete [] myints;
// display the doubles
for (int i = 0; i < size; i++) {
cout << mydoubles[i] << endl;
}
// delete the ints array
delete [] mydoubles;
}