UMBC CMSC201, Computer Science I, Fall 1994
Sections 0101, 0102 and Honors
Tuesday December 6, 1994
Assigned Reading: 13.5 - 14.3
Handouts (available on-line): Quiz 3
Topics Covered:
- Discussed Project 5 and the strategy you should implement.
- Continued discussion of memory allocation.
Our first program used malloc to allocate
an array of 26 characters, which we used to store the
letters of the alphabet. Note that malloc returns
a pointer value, but elements of the array can be accessed
using array notation. Also, when we are done with the block
of memory allocated by malloc we should free it using
the function free.
Program and sample run.
- Our second program using memory allocation uses malloc
to allocate an array of integers. We use the casting operator
(int *) to change the type of the value returned
by malloc from pointer to void to pointer
to int. We also check to see if malloc
successfully allocated the requested amount of space.
(If malloc failed, it returns the NULL value
which is defined to be zero in stdio.h.)
Program and
sample runs.
- In the third program, 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.
- Quiz 3.
Last Modified:
Tue Dec 13 17:02:25 EST 1994
Richard Chang, chang@gl.umbc.edu