Homework Finishing K&R Chapter 5 today Starting K&R Chapter 6 next Skipping sections 5.7-5.9 for now Not covering section 5.12 Starting K&R Chapter 6 next
Pointers to Functions, K&R 5.11 Function prototype with pointer to function void qsort ( … , int (*comp) (void *, void *)); Function call passing a pointer to function qsort( … , (int (*) (void *, void *)) strcmp); This is a cast to function pointer of strcmp Within qsort(), function is called via a pointer if ((*comp) (v[i], v[left]) < 0) … Address of a function Qsort will use comp function. Different sorting functions
Pointers to Functions Initialize a pointer to a function /* function pointer *fooptr = cast of foo to func ptr */ int (*fooptr) (int *, int*) = (int (*) (int *, int *)) foo; Call the function foo via the pointer to it (*fooptr) (to, from); This allows you to pass a function name dynamically to another function. We don’t do much with this concept in this course. END OF POINTERS
structs, K&R 6 A struct is a collection of variables, possibly of different types, grouped under a single name for common reference as a unit. struct point { /* with optional tag */ int x; /* member x */ int y; /* member y */ } pt, q; /* variable names */ or struct { /* w/o optional tag */ int x, y; /* two members */ } pt, q; /* variable names */ Size of them
structs The defined struct point is like a new “type” With the tag, point, can declare other variables: struct point pt1, maxpt = {320, 200}; Reference to struct members: pt1.x = 320; pt1.y = 200; /* alternate init */ printf("(%d, %d)\n", pt1.x, pt1.y); /* prints out as (320, 200) */ Struct.element
structs Defining a struct inside a struct (nesting). struct rect { struct point pt1; /* lower left */ struct point pt2; /* upper right */ }; struct rect box;/* declare box as a rect */ You can First define it then use it
structs pt1 is lower left hand corner of box pt2 is upper right hand corner of box: box.pt1.x < box.pt2.x box.pt1.y < box.pt2.y y box.pt2.y To get area box.pt1.y x box.pt1.x box.pt2.x
structs /* Find area of a rectangle */ int area = rectarea (box); … int rectarea (struct rect x) { return (x.pt2.x - x.pt1.x) * (x.pt2.y - x.pt1.y); }
structs Memory allocation for structs Two point structs pt1 and pt2 One rect struct box containing two point structs pt1 pt2 pt1.x pt1.y pt2.x pt2.y box pt1 pt2 pt1.x pt1.y pt2.x pt2.y