Create a week09 directory in your weeklylab subdirectory and copy over
some files:
cd cs31/weeklylab
pwd
mkdir week09
ls
cd week09
pwd
cp ~kwebb/public/cs31/week09/* .
ls
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:
- The header file(s) you need to include to gain access to the function. For example, if you want to use strchr(), you must include string.h.
- The prototype of the function, including the parameter types and return
type.
- A brief description of what the function does.
- A description of the function's return value. This is particularly
important for functions that use the return value as an indicator of
success/failure, as it will help you to interpret the resulting code.
- A list of other functions that you might need to know about to use this
function, or perhaps alternatives, in the "See Also" section.
Lab 7: Your own string library