User Tools

Site Tools


cs270:cstrings

Exercise - Using C-strings

When doing these exercises in class, please be sure to keep the output of each step to show the instructor at the end. I need to check off progress/completion each day, or get evidence of the completed exercise by end of day.

Objectives

  • Discover how ASCII encodings affect C-string comparisons
  • Investigate one way pointer variables and arrays can be interchangeable
  • Learn how to enter the EOF (end of file) character from the keyboard

Part 1: C-Strings

  1. Download the file cstrings.c
  2. Compile and run to recreate the strcmp issue with “alligator” and “Zebra” described in the C-Strings video lecture. Take note of which string is “greater”.
  3. Edit the file and change the first strcmp call in the comparisons function to strcasecmp. Recompile and run to see how the output changes.
  4. Change the string literals “alligator” and “Zebra” to any other strings you'd like to compare. Include punctuation characters, spaces, etc. The run the program again.

Part 2: Pointer/Array equivalence

In many cases C programmers will use pointers and arrays interchangeably (but not always! King Chapter 13 lists some gotchas). To see an example where this works, do the following:

  1. Download the file maxline.c
  2. Read through it. Note how most arguments to the functions getline1 and copy are passed as arrays. Also note the use of the getchar function.
  3. Compile and run. Type in several lines of input, each a different length.
  4. The program stops reading when it detects the EOF (end-of-file) character. This is automatically added when we save files, but requires special input when typing at the keyboard. At the beginning of a line, hold down the Control key and hit D. This is usually written <Ctrl-D>. Note the output.
  5. Now edit the file. In the function prototypes near the top, and the function definitions near the end, change all three array parameters to pointer variables.For example, change char to[] to char *to.
  6. You won't need to change the function calls at all!
  7. Try to compile and run the program again, using the same input. Does it all work? Think about why it does (or doesn't). King Section 13.2 has some answers.
cs270/cstrings.txt · Last modified: 2020/09/07 17:07 by scarl