Void Pointer
Eike Ritter
School of Computer Science
University of Birmingham
1
Void pointer
• A void pointer in C has no associated data type.
• It can store the address of any type of object
• ‘Generic pointer’
• It can be type-casted to any types.
Syntax for declaration
void *pointer_name;
2
Void pointer and reusability
• Most important feature of the void pointer is reusability.
• We can store the address of any object
• Whenever required we can typecast it to a required type
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;
//Dereferencing void pointer with char typecasting
printf("cData = %c\n\n",*((char*)pv));
//Pointer to int
pv = &iData;
//Dereferencing void pointer with int typecasting
printf("iData = %d\n\n",*((int *)pv));
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;
printf("Value %d\n", *((int *) pv) );
return 0;
}
What will be the output?
5
Arithmetic on void pointer
#include<stdio.h>
int main()
{
int a[4] = {1, 5, 13, 4};
void *pv = &a[0];
pv = pv + 1;
printf("Value %d\n", *((int *) pv) );
return 0;
}
What will be the output?
It will not print 5
pv+1 does not increment pv by scale_factor=4 6
Arithmetic on void pointer
Perform proper typecasting on the void pointer before
performing arithmetic operation.
#include<stdio.h>
int main()
{
int a[4] = {1, 5, 13, 4};
void *pv = &a[0];
pv = (int *) pv + 1;
printf("Value %d\n", *((int *) pv) );
return 0;
}
Now it prints 5
During pv+1 compiler increments pv by scale_factor=4
7
Function pointers
Start address of foo1()
foo1() Program
memory
Start address of foo2()
foo2()
• Every function has a memory address.
• A pointer to a function holds the starting address
12
Function pointer syntax
Syntax for declaration
int (*foo)(int);
• foo is a pointer to a function
• Where function takes one int argument and returns int.
int negate(int a);
foo int square(int c);
...
Foo can point to any of these functions 13
Function pointer syntax: careful
Function pointer declaration
int (*foo)(int);
Here function returns pointer of type int
int *foo(int);
To declare a function pointer ( ) must be used
14
Function pointer syntax
What is the meaning of this syntax?
int *(*foo)(int);
• foo is a pointer to a function
• Where function takes one int argument and returns pointer to int.
int *negate(int a);
foo int *square(int c);
...
Foo can point to any of these functions 15
Initialization of function pointer
void int_func(int a)
{
printf("%d\n", a);
}
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