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'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.
There must be a way to avoid duplicating code like this.
Easy! Just write a
normalize
helper function!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!
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.
Oh, no! So we can't have a helper function?
We can, we just need to learn some new stuff to figure out how.
MORE concepts??!! Oh yeah!!
Before we get into the new stuff, let's review some material from Week 2, Lesson 2.
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 float
s.
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 i
—myArr[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 ofi
from the address given bymyArr
.- Thus
*(myArr + i)
gives you the value at the address of the item at indexi
.
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.)