CS31 Weekly Lab: Week 9

Writing C libraries: .c and .h files, C strings

Create a week09 directory in your weeklylab subdirectory and copy over some files:

    cd cs31/weeklylab
    mkdir week09
    cd week09
    cp ~kwebb/public/cs31/week09/* .

Writing a C library

To start off, we're going to learn how to write a C library and how to use it in a program. Let's take a look at mylib.h, mylib.c, and prog.c, a program that uses them.

Tia has written some good documentation on creating libraries in C. I would suggest referring to that if you need to brush up on any details.

Strings and Pointers in C

Let's look at the file ptrarth.c. This code contains some examples of using a pointer to iterate over arrays of char and arrays of ints. It uses pointer arithmetic to adjust the pointer at each step to point to the next bucket. Adding a value (lets say 3) to a pointer, does not add three to the address value stored in the pointer variable. Instead, it adjusts the pointer the pointer variable to have the address of the the valid storage location of the type it points to that is three locations beyond it. For example:
int array[10], *ptr, *start, num;

ptr = array;
start = ptr;

*ptr = 6;  // puts 6 in bucket 0 of the array
ptr = ptr + 3;  // make ptr point to bucket 3 of the array
                // which is at address 12 beyond the current value of ptr
*ptr = 8;  // puts 8 in bucket 3 of the array

num = ptr - start;  //

In the example code, using pointer arithmetic is not necessary (the same functionality can be accomplished without using pointer arithmetic), but it is handy to use in some cases.

Let's try out the first TODO item in this file and run and test it.

Man Pages (You'll be reading these for the lab assignment.)

Now let's look at the man page for strchr and for isspace, then let's try out the second TODO and test it out.

When reading man pages, there are certain key pieces of information you'll want to look at:

Lab 7: Your own string library