CPSC 225, Spring 2002
Quiz #3, March 22

This is the third quiz in CPSC 225: Intermediate Programming.


Question 1: Suppose that ptr is a variable of type int* (that is, of type pointer to int). What would you expect &*ptr to represent? Explain your answer.

Answer: The value of the expression &*ptr is the same as the value of ptr. That is, it is a pointer to an int that points to the same memory location as ptr. Since ptr is a pointer, *ptr is a name for the thing that it points to. The & is the address operator. It returns a pointer to the thing to which it is applied. Thus, &*ptr is "a pointer to the thing to which ptr points," which just says that it's the same as ptr.

(All this assumes that ptr is non-NULL. If it is NULL, then *ptr is undefined and so is &*ptr.)


Question 2: Assume that BigInt is some class. Explain the following declaration. What does it mean? What does it allow you to do in your program?

       BigInt operator+(const BigInt x, const BigInt y);

Answer: This is an example of operator overloading. It extends the addition operator so that it can be used to add two BigInt objects, yielding a BigInt object as the result. This allows me to use the expression "A + B" whenever A and B are variables or expressions of type BigInt.


Question 3: Suppose that the following declarations are used to represent a simple linked list of integers:

   struct ListNode {
      int item;
      ListNode *next;
   }

   ListNode *head;

What is the purpose of the following code? Assume that the list is not empty.

   ListNode *node = head;
   while (node->next != NULL) {
      node = node->next;
   }

Answer: This positions node so that it points to the last item in the list. (At the time the while loop ends, we know that node is not NULL but that node->next is NULL. This means that we are at the end of the list.)


Question 4: This question uses the same declarations of ListNode and head that were given in the previous question. Write a code segment that will add up all the integers in the list. (If the list is empty, the sum should be 0.)

Answer:

             int sum = 0;   // This will be the sum of all the list items.
             ListNode *runner = head;   // So we don't lose the list!
             
             while (runner) {   // Could also say "while (runner != NULL)".
                sum = sum + runner->item;
                runner = runner->next;
             }

David Eck, eck@hws.edu