Title: Void and Function Pointers
1Void and Function Pointers
2Outline
- Void Pointers
- Function Pointers
3Void Pointers
- We talked about void pointers in an earlier
lecture - We stressed some things not to do
- We also mentioned that they had useful purposes
- For example
- malloc returns a void
- It is just returning a pointer to some newly
allocated space - The space has no associated type
- The programmer must make that association by
assigning the returned value into the appropriate
type pointer - Since this type isn't known to the author of
malloc it returns the generic void
4Another Example
- One of the problems with the standard swap( )
function is that it is "hard-wired" to a
particular type (i.e. we must know ahead of time
that we are swapping two ints, or two floats,
etc). - Write a swap( ) function that will swap two items
of arbitrary size. Your function will need to
accept a third parameter, which is the sizeof the
two items to be swapped. Do not use any library
calls in your solution.
5- / Is this okay???
- 1 Yes
- 2 No /
- void swap(void a, void b, size_t size)
-
- int i
- for(i0 iltsize i)
-
- char t ai
- ai bi
- bi t
-
6- void swap(void a, void b, size_t size)
-
- char ap a
- char bp b
- int i
- for(i0 iltsize i)
-
- char t api
- api bpi
- bpi t
-
7- int a 42
- int b 78
- double d1 56.90
- double d2 392.4567
- swap(a, b, sizeof(int))
- swap(d1, d2, sizeof(double))
- Node n1
- Node n2
- / assume we initialize the nodes /
- swap(n1, n2, sizeof(Node))
8Questions?
9Function Pointers
10What is...
- A variable?
- A symbol representing an address where we store
something - An array variable?
- A symbol representing an address where a block of
memory has been reserved - A function name?
- A symbol representing the address of a piece of
code which we can jump to (and we normally expect
it will contain code that will return control to
the caller.) - Assembly language for int fact(int n)
- fact save sp, -112, sp Beginning of
- fact function
11If we...
- Want to store the address of a variable we use a
pointer (e.g. int ip) - Same is true for holding the address of a
function - int fi(void) / Function that returns an int
/ - int fpi(void) / Function that returns a
pointer - to an int
/ - (int )fpi(void) / What compiler sees (sort
of!) / - int (pfi)(void) / Declaring pfi to be a
pointer to - a function!
/
12Using it...
- int fi(void) / Function that returns an int
/ - int fpi(void) / Function that returns a
/ - / pointer to an int
/ - int (pfi)(void) / Declaring pfi to be a
/ - pointer to a function!
/ - pfi fi / Legal assignment
/ - pfi fi() / NO NO NO NO NO NO NO NO NO
NO / - Notice similarity to
- int ia10
- int ip
- ip ia
13Using it (Part Deux)...
- i fi()
- i (pfi)()
- i pfi()
- Note pfi() would mean call the function which
would return an int and then dereference it!
- int fi(void) Â Â Â return 42
- int main() Â Â Â int t1, t2, t3Â Â Â int (pfi)
(void)   pfi fi   t1 fi()   t2
pfi()Â Â Â t3 (pfi)()Â Â Â printf("d d
d\n", - t1, t2, t3)Â Â Â return 0
- Â
- ./fp42 42 42
14Review
15Review
- int somefunction(int i)
-
- return i2
-
- int main()
-
- int j
- j somefunction(j)
- ...
16Review
17Review
- void anotherfunction(int ip)
-
- ip ip 2
-
- int main()
-
- int i
- void anotherfunction(i)
- ...
18What we just said...
- float f
- float fdiv(int a, int b) return (float)a/b
- float (functionpointer)(int, int)
- functionpointer fdiv
- f functionpointer(13, 16)
19Which means...
- float beta(
- float (functionpointer)(int, int),
- int x, int y )
- return functionpointer(x,y)
-
- float fdiv(int a, int b)
- return (float)a/b
- int main()
- float f
- f beta(fdiv, 10, 12)
- ...
20But what good is a function pointer?
- Say you are writing a general purpose sorting
function. - You want it to be able to sort anything
- Numbers
- Strings
- ???
- Obviously comparing numbers and strings calls for
two different techniques - What if we write functions that do the comparison
we need - A function to compare numbers
- A function to compare strings
- A function to compare ???
21But what good is a function pointer?
- Now when we call the function to do the sorting
we pass in a pointer to the appropriate function
for the type of data we have! - "But wait," I hear you say, "It would be easier
to write my own sorting function!"
22- qsort(3)
qsort(3) - NAME
- qsort - sort an array
- ANSI_SYNOPSIS
- include ltstdlib.hgt
- void qsort(void base, size_t nmemb,
size_t size, - int ( compar)(const void , const void )
) - TRAD_SYNOPSIS
- include ltstdlib.hgt
- qsort( base, nmemb, size, compar )
- char base
- size_t nmemb
- size_t size
- int ( compar)()
nmemb
base
size
23- qsort(3)
qsort(3) - DESCRIPTION
- qsort sorts an array (beginning at base)
of nmemb objects. - size describes the size of each element of
the array. - You must supply a pointer to a comparison
function, using - the argument shown as compar. (This
permits sorting - objects of unknown properties.) Define
the comparison - function to accept two arguments, each
a pointer to an - element of the array starting at base.
The result of - (ltcompar)gtgt must be negative if the
first argument is - less than the second, zero if the two
arguments match, and - positive if the first argument is greater
than the second - (where less than'' and greater than''
refer to what- - ever arbitrary ordering is appropriate).
- The array is sorted in place that is,
when qsort returns, - the array elements beginning at base have
been reordered.
24- qsort(3)
qsort(3) - RETURNS
- qsort does not return a result.
- PORTABILITY
- qsort is required by ANSI (without
specifying the sorting - algorithm).
- SOURCE
- src/newlib/libc/stdlib/qsort.c
25QSort Demo
- include ltstdlib.hgt
- void qsort (
- void base,
- size_t nmemb,
- size_t size,
- int ( compar)(const void , const void )
- )
- The result of "compar" must be negative if the
first argument is less than the second, zero if
the two arguments match, and positive if the
first argument is greater than the second (where
"less than" and "greater than" refer to whatever
arbitrary ordering is appropriate).
26- include ltstdio.hgt
- include ltstdlib.hgt
- define MAX 100
- int compar_ints(const void pa, const void pb)
- return ((int )pa) - ((int )pb)
-
- int compar_strings(const void ppa, const void
ppb) - return strcmp( ((char )ppa) , ((char )ppb)
) -
-
27- define MAX 100
- int main(int argc, char argv)
- char strings "dec", "sun", "ibm", "apple",
"hp", "ti", "univac" - int i, s
- int aMAX
- if(argc 2 (argv1) 'a')
- s sizeof(strings)/sizeof(strings0)
- qsort(strings, s, sizeof(strings0),
- compar_strings)
- for(i 0 i lt s i)
- printf(" s", stringsi)
-
- printf("\n")
-
- else...
28- else
- for(i 0 i lt MAX i)
- ai rand() 100
- printf(" d", ai)
-
- printf("\n\n")
- qsort(a, MAX, sizeof(int),
- compar_ints)
- for(i 0 i lt MAX i)
- printf(" d", ai)
-
-
- return 0
-
29Questions?
30But what good is a function pointer?
- Okay, so sorting is one application. How about
another??? - Imagine we are writing a routine to traverse a
data structure - What exactly do we do at each node?
- print it?
- modify it?
- test it?
31But what good is a function pointer?
- What if we passed into our traversal routine a
pointer to a function which did what needed to be
done??? - Advantage No need to continually modify our
traversal routine. It's now generic!
32Basic Treenode with Root Pointer
- struct treenode
-
- char itemName
- int itemCount
- struct treenode left, right
-
- struct treenode root NULL
- int totalItems
33Post Order Traversal
- void
- postOrder( struct treenode theNode,
- void ( doThis )( struct treenode ) )
-
- if( theNode NULL )
- return
- postOrder( theNode-gtleft, doThis )
- postOrder( theNode-gtright, doThis )
- doThis( theNode )
34Closer Look
- void
- postOrder( struct treenode theNode,
- void ( doThis )( struct treenode ) )
- Note This function "postOrder" take two
parameters - A pointer to a treenode
- A pointer to a function
35Closer Look
- void
- postOrder( struct treenode theNode,
- void ( doThis )( struct treenode ) )
Function Pointer
Parameter list for function
Return value of function
36Counting Function
- void
- countItems( struct treenode theNode )
-
- totalItems theNode-gtitemCount
-
37Printing Function
- void
- printItems( struct treenode theNode )
-
- printf( "s d\n", theNode-gtitemName,
theNode-gtitemCount ) -
38Less than 5 items Function
- void
- checkItems( struct treenode theNode )
-
- if( theNode-gtitemCount lt 5 )
- printf( "s\n", theNode-gtitemName )
-
39Clear Items Function
- void
- clearItems( struct treenode theNode )
-
- theNode-gtitemCount 0
-
40Free Nodes Function
- void
- freeNodes( struct treenode theNode )
-
- free( theNode-gtleft )
- free( theNode-gtright )
- free( theNode-gtitemName )
-
void postOrder( struct treenode theNode, void (
doThis )( struct treenode ) ) if(
theNode NULL ) return postOrder(
theNode-gtleft, doThis ) postOrder(
theNode-gtright, doThis ) doThis( theNode
)
41Main Function
- int
- main( void )
-
- root buildTree( )
- totalItems 0 / Global /
- postOrder( root, countItems )
- printf( "There are d items.\n",
- totalItems )
42Main Function
- printf( "List of all the items and"
- " how many there are\n" )
- postOrder( root, printItems )
- printf( "The following items are in"
- " short supply\n" )
- postOrder( root, checkItems )
- / clear itemCount for all items /
- postOrder( root, clearItems )
43Main Function
- / free all nodes /
- postOrder( root, freeNodes )
- free(root)
- return EXIT_SUCCESS
-
44NOTE
- Function Header
- void
- postOrder( struct treenode theNode,
- void ( doThis )( struct treenode ) )
- Function Call
- doThis( theNode )
- Function Header
- void
- countItems( struct treenode )
- Function Call
- postOrder( root, countItems )
45What's the difference?
- LLNode (llnpfp) (LLNode , int )
- typedef LLNode (llnfp_t) (LLNode , int )
46Function that returns a function pointer
- float (GetPtr1(const char opCode))(float, float)
- The function name and parameters
- float (GetPtr1(const char opCode))(float, float)
- The return value for the function
- float (GetPtr1(const char opCode))(float, float)
- float (GetPtr1(const char opCode))(float, float)
-
- if(opCode '') return add
- if(opCode '-') return sub
- else return mult
47Additional Information
- http//www.function-pointer.org/
- Don't let the C stuff confuse you!
48Questions?
49(No Transcript)