CS 202 - Notes 2016-02-22

Arrays and functions

We have three ways to pass arrays to functions as shown in 05-maxarrays.c. My advice is to use the version that makes it explicit you are passing an array and pass the length as a second parameter to the function.

We skipped over this in class, but arrays can be returned from functions as well. However, at the moment we don’t know who to dynamically allocate memory so the array would be created in a memory location that is no longer available after the function you are returning from returns. So don’t do this (at least not until we know how to dynamically allocate memory).

Strings

Strings are just character arrays in C. So their “type” is basically char *.

Strings do not have to be the same length as the amount of array space that has been allocated for them. We indicate the end of a string with the NULL character, which can be represented as the character '\0' or the value 0. As I said in class, this is one of the worst decisions in the history of computing. It has led to enormous problems as a source of bugs and exploits.

We looked briefly at the functions available in string.h. You should spend some time figuring out how to use them. I pointed out that many of them are found in two forms: str* and strn*. You should always use the strn* form, as those allow you to be explicit about the length of the string rather than relying on the '\0' to be present.

Aside: Randomness

We used rand() to generate some random numbers for our arrays. This led to a short discussion about randomness. There are no real random numbers – what we can generate in the computer are “pseudo-random”. They are generated by a mathematical formula that meanders over a set of numbers. The appearance of randomness comes from how the walk is initialized. In C, the random seed is not automatically initialized (or rather it defaults to 1), so we will always get the same sequence of results from rand(). To set a new seed in C, we use the srand() function. Calling srand() with different values before you start generating random numbers will result in different sequences. It is typical to pass in the current time (time(NULL)), which will give you the appearance that every time you run your program you get a different sequence of numbers.