Graphics Programs Reference
In-Depth Information
While struct memory can be accessed this way, assumptions are made
about the type of variables in the struct and the lack of any padding between
variables. Since the data types of a struct's elements are also stored in the
struct, using proper methods to access struct elements is much easier.
0x285
Function Pointers
A pointer simply contains a memory address and is given a data type that
describes where it points. Usually, pointers are used for variables; however,
they can also be used for functions. The funcptr_example.c program
demonstrates the use of function pointers.
funcptr_example.c
#include <stdio.h>
int func_one() {
printf("This is function one\n");
return 1;
}
int func_two() {
printf("This is function two\n");
return 2;
}
int main() {
int value;
int (*function_ptr) ();
function_ptr = func_one;
printf("function_ptr is 0x%08x\n", function_ptr);
value = function_ptr();
printf("value returned was %d\n", value);
function_ptr = func_two;
printf("function_ptr is 0x%08x\n", function_ptr);
value = function_ptr();
printf("value returned was %d\n", value);
}
In this program, a function pointer aptly named function_ptr is declared
in main() . This pointer is then set to point at the function func_one() and is
called; then it is set again and used to call func_two() . The output below shows
the compilation and execution of this source code.
reader@hacking:~/booksrc $ gcc funcptr_example.c
reader@hacking:~/booksrc $ ./a.out
function_ptr is 0x08048374
This is function one
value returned was 1
Search WWH ::




Custom Search