Lecture notes for CSC 173, Tues September 24, 2002 ------------------------------------------------- Project 2 is on the web ------------------------------------------------- ======================================================================== Yesterday's speaker: Doug Lea. Three things that will go away: Active X, Corba, C++ Note, not C! ================ Last time: function calls I/O types/structs Today: Boolean memory management arrays and pointers ----------- NOTE: No BOOLEAN type in C 0 = false, everything else = true ptr: nil is false (addr 0), anything else is true comparison ops (==, !=, <, >, <=, >=) return 0 or 1. Beware the pitfall: if (A = B) { ... This sets A equal to B and then does what's in the braces if the copied value is non-zero. Almost never what you want. -------- memory management (lack of garbage collection) void *malloc void free typical syntax: int *foo = (int *) malloc (10 * sizeof (int)); ... free (foo); NB: declarations must all be at the beginning of their scope; they can't be intermixed with code as in Java (or C++) arrays and pointers variable definitions (global or local) (these allocate space): int foo[100]; /* 100-element array of integers */ int *foo; /* pointer to integer (or to element of integer array) */ code: foo[10] /* works with EITHER variable definition */ /* correct with latter only if foo refers to an array with at least 11 elements (indices start at zero, as in Java) */ parameter declarations (in a function prototype [header]) (these do NOT allocate space): int foo[100] /* parameter is a pointer to a 100-elem int array */ int foo[] /* don't actually have to know the size */ int *foo /* equivalent parameter declaration */ NB: declarations of extern arrays allow missing sizes, as in parameter declarations. 2D v. row-pointer array layout variable definitions: int foo[10][10]; /* 10x10 array of integers, contiguous layout */ int *foo[10]; /* 10-elem array of pointer to ints. This is a DIFFERENT LAYOUT, and more like Java */ code: foo[3][4] /* works with EITHER definition */ parameter declarations: int foo[10][10] /* 10x10 array of integers, contiguous layout */ int foo[][10] /* don't have to know size of first dimension */ int foo[10][] /* ERROR: must know size of second dimension */ int *foo[10] /* row-pointer layout */ int *foo[] /* don't have to know size */ int **foo /* equivalent parameter declaration */