CS 12 Homework Assignment 4


CS 12 Homepage
This assignment is due on Monday, August 11, 2003, at the start of the lecture. Please hand in printed solutions. Note: some of the questions in this assignment involve concepts which we will not cover until Monday's lecture. You should be able to answer them, however, if you have done the assigned readings.

1. If a memory address is actually a positive integer number and since pointer variables hold memory addresses as their values, why aren't all pointer variables considered variables of type unsigned int ? There are at least two reasons.

2. Describe when the use of the -> operator is appropriate. Do the same with the . operator.

3. Given the structure Pair below, representing an ordered pair of integers,
struct Pair
{
    int first;
    int second;
};
correct the following snippets of code, or if there is nothing wrong, say there is nothing wrong:
(a)
Pair * pair;
pair.first = 0;

(b)
Pair[] pairs;
pairs[0] -> first = 0;

(c) 
Pair pairs[5];
*pairs.first = 0;

(d)
Pair * pairs[5];
(*pairs).first = 0;

(e)
Pair * p = Pair[5];
p -> first = 0;

(f)
Pair & p = new Pair[5];
p -> first = 0;
4a. What is another name for the variable &a[0] ?

4b. If a is an array variable, what is another name for *a ?

5. Run the following function (by embedding it in a program of your own) and explain what the output is, and why:
void print(int a[], unsigned int length)
{
    for (unsigned int i = 0; i < length; ++i)
    {
        std::cout << *(a + i) << "\r";
    }
}
6. This one is a little tricky. What does the following function compute? Explain your answer.
int f(int a[], unsigned int length)
{
  int x = *a, *b = a;
  while (b != a + length)
  {
    if (*b > x)
        x = *(b++);
    else
        b++;
  }
  return x;
}

© 2003 UC Riverside Department of Computer Science & Engineering. All rights reserved.