• Assignment 5
– Q&A; extended the due date to Sunday night
(problem solving approach) for autoguess intelligence -
should be based on a learning approach - e.g. don’t make the same
mistakes twice; and use the frequency table given.
Otherwise it is
totally up to you.
KISS principle to start.
• Topics for today
Finish function pointers
Advanced declarations (Ch. 18)
, 3, 6
12: 1, 10
, 14, 18
14: 1, 4,
, 6, 8,
22: 1, 16
26: 5, 10
The qsort Function
• Certain functions in the C standard library require a function
pointer as a parameter.
• One of the most commonly used is qsort, a general-purpose
algorithm capable of sorting any array.
• The following declaration for qsort appears in <stdlib.h>:
(void *base, size_t num, size_t size,
int (*compar) (const void *p, const void *q));
• base is a pointer to the first element in the array.
• num is the number of elements in the array.
• size is the size of each array element.
is a pointer to a function that compares two array
elements pointed to by parameters p and q.
• By convention, when given two pointers p and q to array
returns a number that is
– Negative if *p is “less than” *q.
– Zero if *p is “equal to” *q.
– Positive if *p is “greater than” *q.
How to use qsort to sort the inventory array by part #:
First, write a function that compares 2 given elements in the array
int cmp_parts (const void *p, const void *q)
if (((struct part *)p)->part_no < ((struct part *)q)->part_no)
else if (((struct part *)p)->part_no ==
((struct part *)q)->part_no)
Pass the comparison function name to qsort when called
qsort (inventory, num_parts, sizeof(struct part),
/* Inventory example */
#define NAME_LEN 25
#define MAX_PARTS 1000
/* assume it is filled with values*/
- each variable (and function) has only
one definition which causes its memory space to
be allocated, and its value to be initialized
- informs the compiler that we need
access to a named variable (or function), but
doesn’t cause it to allocate memory space
• A given statement can be both
tells the C compiler about the properties of
variables and/or functions.
• Declarations have the form
declaration-specifiers declarators ;
is one of the following:
• Storage class specifier (auto, static, extern, or register)
• Type specifier (e.g.
long, short, unsigned, int, or float)
• Type qualifier (const or volatile)
• At most one storage class is allowed; if present, it comes first
• There may be several type specifiers and/or qualifiers;