#include <stdio.h>
typedef enum
{
red,
green,
blue,
}color_type;
static int choose(void *type_p);
static int test(void *value);
int main(int argc, char **argv)
{
void *void_p;
/*test 1: size of void pointer and size of object void pointer points to*/
printf("Size of the void pointer is %d.\n", sizeof(void_p));
printf("Size of the pointed object is %d.\n", sizeof(*void_p) ); //result is 1. In GNU, void pointer is treated same as char pointer
/*test 2: relation between void pointer and other type pointer*/
int var = 9;
int *num_p = &var;
void_p = num_p;
*(int *)void_p = 10;
printf("Value of the pointer object num_p is %d.\n", *num_p);
printf("Value of the pointer object is %d.\n", *((int *)void_p)); //result is 9, Be care to cast it to other type pointer
/*test 3: pass parameter to a function, */
choose((void *)20);
int aa = 10;
test((void *)aa);
/*test 4: void pointer arithmetic, void pointer is treated same as char pointer*/
char a[5] = "abcd";
int i = 0;
void_p = a;
for(; i < 5; i++)
{
printf("Value of *(a)void_p is %c.\n", *(char *)void_p++);
}
return 0;
}
static int choose(void *type_p)
{
int type = (color_type)type_p; /*void type converts to enum type */
switch(type)
{
case 0:
printf("You choose red!\n");
break;
case 1:
printf("You choose green!\n");
break;
case 2:
printf("You choose blue!\n");
break;
}
return 0;
}
static int test(void *value)
{
printf("Value is %d.\n", (int *)value); // the same as printf("Value is %d.\n", value);
return 0;
}