CSC 161 Grinnell College Fall, 2011
Imperative Problem Solving and Data Structures


Laboratory Exercise on Addressing and the Address Operator

The & Operator

Certain variable types, such as arrays, are always passed in by reference. Primitive data types, such as ints, chars, and doubles, are passed by value by default. However, you can also pass in primitive data types by reference using the & operator.


  1. Look over amp-examp.c and write a few sentences explaining what it does, and why it is possible.

Primitives By Reference

  1. Copy program rand-beep.c into your directory for this lab and run it a few times to see what it does.

  2. Write a few sentences explaining what the program is doing, making sure include the following points:

    • Point out every time a primitive value is passed in by reference to a function.

    • Note how values passed in by reference are called within the function.

    • What durations are possible for the robot to beep for?

    • What frequencies are possible for the robot to beep for?

    • When will the loop end?


  1. Copy get-ir.c into your directory for this lab and write a few sentences explaining what the program is doing.

  2. Complete the parts of the program which say "code here!". It should only require one line of code at each spot, and there are three locations where you must add code.

    • Hint: If you are getting the warning "assignment makes pointer from integer without a cast", try putting * (an asterix) in front of the integer you are assigning to.

Multiple Return Values

  1. Copy mult-ret.c into your directory for this lab and answer the following questions:

    • Is the program currently using the arrays or the int variables to display the light and obstacle sensors?

    • Would you be able to modify the program so that it doesn't use any arrays?

  2. Modify the program so that instead of taking in arrays, set_lights and set_obsts take in three integers addresses (light0, light1, light2) and (obst0, obst1, obst2) and set them to the appropriate values. These values should then be printed in the printf statements. There should be no arrays in your new version of the program. You will no no longer be able to use rGetLightsAll() and rGetObstacleAll().

Indicating Function Success

  1. Write a simple function which finds the square root of a number. It will have the following signature: int safe_sqrt (double * num).

    • It will use the double sqrt(double num) function from the math.h library to find the square root of num. Make sure you compile with the -lm flag when using sqrt().

    • If num is zero or positive, your function will modify num to be its square root and return 1 to indicate success.

    • If num is negative, your function will not modify num and return 0 to indicate failure.

    • You will have to use the & operator when calling your function so that num is passed in by reference.