CS 70

Before You Start

Look back over your code for Homework 2—specifically, the code for plotExampleData() and plotStudentData()—and how you normalized the data in both functions, do you notice anything that might be considered suboptimal style?

What about your code for the two plotting functions in Homework 2 might be suboptimal from a style perspective?

What's Wrong?

In the instructors' solution to the homework (and probably in yours), these lines were basically identical in both functions:

float biggest_val = vals[0];
for (int i = 0; i < TEMPERATURE_SAMPLE_COUNT; ++i) {
    if (vals[i] > biggest_val) {
        biggest_val = vals[i];
    }
}

for (int i = 0; i < TEMPERATURE_SAMPLE_COUNT; ++i) {
    vals[i] = vals[i] / biggest_val * available_height;
}

The only difference was that one (shown above) worked on an array with TEMPERATURE_SAMPLE_COUNT (365) samples, and the other (not shown) worked on an array with POPGROWTH_SAMPLE_COUNT (59) samples.

  • Cat speaking

    There must be a way to avoid duplicating code like this.

  • Duck speaking

    Easy! Just write a normalize helper function!

  • Horse speaking

    Hold your horses! The arrays are different sizes, and the size is part of the type. We can't write one function that takes two different types!

  • LHS Cow speaking

    That's right. Remember, C++ figures out how much stack space a function needs when it compiles the function, not when the function is called.

  • Hedgehog speaking

    Oh, no! So we can't have a helper function?

  • LHS Cow speaking

    We can, we just need to learn some new stuff to figure out how.

  • Pig speaking

    MORE concepts??!! Oh yeah!!

Before we get into the new stuff, let's review some material from Week 2, Lesson 2.

What's the alternative syntax for vals[i]?

A Rapid Recap of Week 2, Lesson 2

Here's what we told you a couple of weeks ago.

Say we make an array of floats.

float myArr[3]{1.2, 3.4, 5.6};

Key Ideas:

  • If we try to get the value of myArr, you might think it would be {1.2, 3.4, 5.6}, but that isn't one value, it's three values. Instead, you get a memory address.
  • Specifically, it is the memory address of the first item in the array.
    • In general, the memory address of something that takes up multiple slots is the memory address of the first item in the thing.
  • So in our memory model the value of myArr is S1.

Usage:

To access the item at index imyArr[i],

  • myArr[i] is translated to *(myArr + i).
  • For a memory address m, saying *m gives you the value at that address.
  • myArr + i is the address at an offset of i from the address given by myArr.
  • Thus *(myArr + i) gives you the value at the address of the item at index i.

The upshot of these rules is that you cannot pass a “whole array” into a function. If you try, it won't work: the name of the array will decay into the memory address of the first item in the array.

(When logged in, completion status appears here.)