Sections 0101, 0102, 0103 and Honors, Fall 1995
Thursday November 30, 1995
Assigned Reading: 13.5 - 14.3
Handouts (available on-line): none
Topics Covered:
- For fun:
a very unclear program
which produces an interesting output.
Unfortunately the author of the program misspelled "eighth" as
"eigth" in this program. Just imagine having to figure out
how to correct the program!
- We continued looking at dynamicaly changing the number of
elements in an array. In our third example, we want to allow
the user to enter a list of positive numbers and use -1 to indicate
the end of the list. In this case, we do not know ahead of time
how large to make the array. Our strategy is to first allocate
an array of 10 elements. If the user enters more than 10 elements,
we allocate an array with 20 elements and copy the first 10 elements
into the new array. We proceed with this strategy and double the
size of the array every time the user exceeds the size of the current
array. We double the size of the array because this is much faster
than increasing the size of the array by 1.
See Program and
sample run.
- In our fourth example of memory allocation,
we use the NewArray
and FreeBlock functions from the course library
instead of malloc and free. These functions
do the error checking for you. We allocate a 27 character
array to store the letters of the alphabet followed by
the null character '\0'. This character signals
the end of a string. In fact, the strings we have been
using all along are really pointers to dynamically allocated arrays
of characters. Thus, at the end of the program we can print
out the characters in our array using %s.
Program and sample run.
- Knowing that strings are really dynamically allocated arrays
allows us to access the elements of the array and change them
directly. For example, we can now write an implementation
of the Captain Crunch secret decoder ring much easier.
Program and
sample run.
- Also we now have more efficient ways to examine every
character in a string. The following program shows
three ways of translating each character in a string to
upper case. They all do the same thing, but some of the
methods are much slower.
Program and
sample run.
- We discussed how the course's string library handles
memory allocations for strings.
Last Modified:
Fri Dec 1 16:45:59 EST 1995
Richard Chang, chang@gl.umbc.edu