Discussion Week 5 Overview Quiz opendir/readdir/closedir/stat pattern matching Debugging techniques programatic Debuggers Function pointers ----------------------------------------------------- Quiz Function Pointers sort example char *names[] = { "zack", "bob", "alice" } void bsort (char *v[], int size) { int i,j; for (i=0; i < size; i++) for (j = i+1; j < size; j++) if (strcmp (v[i], v[j]) > 0) swap (v[i], v[j]); } But now I have a struct struct person { char name[32]; int age; }; typedef int (*comp_fct) (void *, void *); void bsort (struct person *v[], int size) { int i,j; for (i=0; i < size; i++) for (j = i+1; j < size; j++) if (strcmp (v[i]->name, v[j]->name) > 0) swap (v[i], v[j]); } Note : Need only change compare function (the rest stays the same. What about if I wanted to sort on age, --> need to change the compare function typedef int (*comp_fct) (void *, void *); void bsort (struct person *v[], int size, comp_fct compare) { int i,j; for (i=0; i < size; i++) for (j = i+1; j < size; j++) if ((*compare) (v[i], v[j]) > 0) swap (v[i], v[j]); } int person_compare (void *v1, void *v2) { struct person *p1 = (struct person*)v1; struct person *p2 = (struct person*)v2; return strcmp (p1->name, p2->name); // or if (p1->age < p2->age) return -1; if (p1->age > p2->age) return 1; return 0; } Debugging Techniques printf Simple printf ("X = %d \n"); DEBUG macros #define DEBUG(X) printf X DEBUG(("X = %d\n")); Turn off debugging by simply #define DEBUG(X) levels Sometimes you need levels of report extern int dlevel; #define DEBUGL(L,X) do { if (dlevel > (L)) printf X ; } DEBUGL(10, ("low priority X=%d\n")); DEBUGL(1, ("high pri X=%d\n")); assert Assert something is about the state of your program. #include int fact (int x){ assert (x>=0); ... GDB http://www.cs.ucsb.edu/Facilities/Software/gdb.html starting Compile all programs with -g gcc -g -c board.c main.o gcc -g -o mancala board.o main.o gdb mancala or run under xemacs M-x gdb gdb> run break points break main ; set a break point cont ; continue steping step ; step (into next function) next ; next statment finish ; finish running function printing print x ; print the value of x display x ; show the value of x every time stop Stack trace where (bt) ; Show active function calls up down stoping bye C-c ; sends a signal to the program DDD Graphical debugger based