Week3.2void and Function Pointers
Week3.2void and Function Pointers
Eike Ritter
School of Computer Science
University of Birmingham
1
Void pointer
• ‘Generic pointer’
void *pointer_name;
2
Void pointer and reusability
3
Void pointer example
int main()
{
void *pv;
int iData = 5; The same pointer is reused for
char cData = 'C'; multiple data types.
Type must be specified while
//Pointer to char dereferencing.
pv = &cData;
//Pointer to int
pv = &iData;
return 0;
} 4
Arithmetic on void pointer
#include<stdio.h>
int main()
{
int a[4] = {1, 5, 13, 4};
void *pv = &a[0];
pv = pv + 1;
return 0;
}
5
Arithmetic on void pointer
#include<stdio.h>
int main()
{
int a[4] = {1, 5, 13, 4};
void *pv = &a[0];
pv = pv + 1;
return 0;
}
int main()
{
int a[4] = {1, 5, 13, 4};
void *pv = &a[0];
pv = (int *) pv + 1;
return 0;
}
Now it prints 5
During pv+1 compiler increments pv by scale_factor=4
7
Function pointers
12
Function pointer syntax
int (*foo)(int);
int (*foo)(int);
int *foo(int);
int *(*foo)(int);
int main()
{
void (*foo)(int);
// & is optional
foo = &int_func;
return 0;
}
16
Calling function using function pointer
void int_func(int a)
{
printf("%d\n", a);
}
int main()
{
void (*foo)(int);
// & is optional
foo = &int_func;
// two ways to call
foo(2);
(*foo)(3);
return 0;
}
17