CS31 Weekly Lab: Week 11

writing C libraries: .c and .h files and linking, C strings

Week 11 lab goals:

  1. Learn about writing C library code
  2. Learn about linking libraries into programs
  3. Discuss differences between .c and .h files
  4. Refresh and go further into strings in C

Create a week11 subdirectory in your weeklylab subdirectory and copy over some files:
    cd cs31/weeklylab		
    pwd
    mkdir week11
    ls
    cd week11
    pwd
    cp ~lammert/public/cs31/week11/* .
    ls
    Makefile  mylib.c  mylib.h  prog.c  ptrarith.c

Writing a C library
We are going to learn how to write a C library and how to use it in a program.
First, let's look at my page on Libraries in C. We are going to look at the "CREATING AND USING YOUR OWN LIBRARY CODE" part of this and then look at some example C library code in mylib.[ch] and an example program that uses it (prog.c).

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.

This code also shows an example of using the readline library to read in a string entered by the user. I have some documentation about the readline library here: using the C readline library

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

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.