CS31 Weekly Lab: Week 8

Command line arguments, 2-D arrays, file I/O, and Makefiles


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

    cd cs31/weeklylab
    pwd
    mkdir week08
    ls
    cd week08
    pwd
    cp ~kwebb/public/cs31/week08/* .
    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. The first thing to note is the change in main's definition:

int main(int argc, char **) { ...

The first parameter to main, argc, is the number of command line arguments. For example, if the user enters:

./a.out 10 11 200

Here, argc will be 4 (the name of the program "a.out" counts as one of the command line arguments, and 10, 11, and 200 are the other three).

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)
        -----

Often, you don't want the string "10", but instead an integer whose value is 10. (In Python, you'd use int() to do the conversion.) C has similar functions that can convert ASCII strings of numeric characters to their int, float, and other basic type values. If you want to convert from an ASCII string to an integer, you'd used atoi, which stands for "ASCII to integer".

int x = atoi(argv[1]);  // x gets the int value 10

See the 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

Next, let's open twoDarray.c and 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

Next, we're taking off the training wheels and looking at methods for file I/O using the C stdio library in fileio.c.

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

Lab 6: Conway's Game of Life