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
    mkdir week08
    cd week08
    cp ~kwebb/public/cs31/week08/* .

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:

./prog hello 1234 cs31

Here, argc will be 4 (the name of the program "prog" counts as one of the command line arguments, and "hello", "1234", and "cs31" 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]:| *-|-----> "./prog"
argv[1]:| *-|-----> "hello"
argv[2]:| *-|-----> "1234"
argv[3]:| *-|-----> "cs31"
argv[4]:| *-|-----|     (NULL pointer: no more command line strings)

Often, you don't want the string "1234", but instead an integer whose value is 1234. (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[2]);  // x gets the int value 1234

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