Take a look at the following code which is an example of using pointers to access a function, an array of characters, and an array of integers. This uses data that is set at compile time, and other data introduced into a block of memory allocated by
malloc
.
#include <stdio.h>
#include <memory.h>
#include <malloc.h>
void fun(int a)
{
printf("Value of a is %d\n", a);
}
int main()
{
char text[] = "Hello, World!"; char* cp = text; for (; *cp != '\0'; cp++) {
printf("%c", *cp);
}
printf("\n\n");
int numbers[] = { 1, 2, 3, 4, 5, -1 }; int* ip = numbers; for (; *ip != -1; ip++) {
printf("%d, ", *ip);
}
printf("\n\n");
void (*fun_ptr)(int) = fun;
fun_ptr(10);
printf("\n\n");
void* vp = malloc(100);
int numbytes = (sizeof(text) / sizeof(text[0])) * sizeof(char); memcpy(vp, text, numbytes);
cp = (char*)vp; for (; *cp != '\0'; cp++) {
printf("%c", *cp);
}
printf("\n\n");
numbytes = (sizeof(numbers) / sizeof(numbers[0])) * sizeof(int); memcpy(vp, numbers, numbytes); ip = (int*)vp; for (; *ip != -1; ip++) {
printf("%d, ", *ip);
}
printf("\n\n");
printf("vp = %p\n", vp);
(void(*)(int))vp = fun; ((void(*)(int))vp)(23);
(char*)vp += sizeof(void(*)(int));
printf("vp = %p\n", vp);
(void(*)(int))vp = fun; ((void(*)(int))vp)(45);
return 0;
}
The final two print statements show that the two dynamic function pointers are at different addresses.