CS31 Weekly Lab: Week 9

command line args, 2-D arrays, file I/O, makefiles, gdb

Week 9 lab goals:

  1. Learn about command line arguments in C and atoi function
  2. Learn how to dynamically allocate 2-D arrays in C
  3. Review file I/O in C
  4. Look at makefiles in more detail
  5. Remind ourselves about gdb and valgrind for debugging

Create a week09 subdirectory in your weeklylab subdirectory and copy over some files:
    cd cs31/weeklylab		
    pwd
    mkdir week09
    ls
    cd week09
    pwd
    cp ~lammert/public/cs31/week09/* .
    ls

command line arguments and atoi
Let's look at an example C program that takes command line arguments. Open commandlineargs.c in an editor:
emacs commandlineargs.c &
The first thing to note is the change in main's definition:
int main(int argc, char *argv[]) { ...
The first parameter to main, argc, is the number of command line arguments. For example, if the user enters:
./a.out 10 11 200
argc will be 4 (a.out counts as one of the command line arguments, and 10, 11, and 200 as three more).

Each command line argument is passed to main in the second parameter, argv, as a string (argv is an array of strings):

        -----
argv[0]:| *-|-----> "./a.out"
        -----
argv[1]:| *-|-----> "10"
        -----
argv[2]:| *-|-----> "11"
        -----
argv[3]:| *-|-----> "200"
        -----
argv[4]:| *-|-----|     (NULL pointer: no more command line strings)
        -----
C has functions that can convert strings of numeric characters to their int, float, and other basic types, values.
int x = atoi(argv[1]);  // x gets the int value 10
See the atoi man page for more information (man atoi).

Let's try compiling and running this program with different command line arguments and see what happens.

dynamically allocated 2-D arrays in C
We are going to look at a three different ways in which 2D arrays can be declared, allocated, and accessed in C.

Here is some more information about arrays in C, including dynamically allocated 2D arrays: Arrays in C

file I/O in C
We are going to look at an example of file I/O in C.

Here is some documentation about file I/O in C: File I/O in C

make and Makefiles
For the next lab, you will write a makefile from scratch to compile your program.

Here is some documentation about writing makefiles: Makefiles I suggest following the simple example here, and/or using a makefile from a previous lab assignment as a starting point.

reminder about gdb and valgrind for C program debugging
We are back to C programming this week, with pointers and functions. You are all experts at using gdb to debug at the assembly level, but remember that you also know how to use gdb (and valgrind) to debug programs at the C code level.

In lab on week 5 we looked at some examples of using both gdb and valgrind. Take a look at the the week 5 weekly lab page and the examples we talked about as a reminder of how to use these debugging tools.

Also, here are links to my guides for gdb, ddd, and valgrind: