UC3M

Telematic/Audiovisual Syst./Communication Syst. Engineering

Systems Architecture

September 2017 - January 2018

5.8.  Pointers to functions

A function pointer is a variable that stores the address of a function. This function can be called later, through the pointer. This type of construction is useful as encapsulates behavior, which can be called through a pointer. Let's see how it works with a simple example that creates a pointer to a function and invokes do_print:

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
void do_print()
{ 
  printf("Printing a message\n"); 
}
int  main()
{
  void (*ptr_funct)(void)=do_print;
  ptr_funct(); //It calls do_print
  return 0;
}

Function pointers are also used for callback functions. The following code snippet shows an example where a function receives as a parameter a function pointer, which invokes when it has completed execution. It also prints out the memory addresses occupied by the functions, which is printed with the %p include in the printf function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
 #include <stdio.h>      
void printf_hello(int x)
{
    printf( "[*HELLO__] Hello number %d\n", x);
}

void printf_bye(int x, void (*ptr_func)())
{
    printf( "[*BYE____] Bye, bye number %d\n", x);
    if(ptr_func!=NULL)
    {
      ptr_func();  //Using the pointer to callback
    }
}

void funct_call_back()
{
    printf( "[*CALLBACK] Callback invoked\n");
}

int main()
{   // Two pointers to functions
    void (*ptr_funct_1)(int)=NULL;
    void (*ptr_funct_2)(int, void (*call_back_funct)() )=NULL;    
    //First pointer
    ptr_funct_1 = printf_hello;
    printf("[*MAIN_] First pointer is %p\n",ptr_funct_1);
    ptr_funct_1(3); 
    //Second pointer
    ptr_funct_2 = printf_bye;    
    printf("[*MAIN_] Using a callback function \n",ptr_funct_2);    
    ptr_funct_2(3,funct_call_back);     
    return 0;
}