GNU下的void指针

#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;
}


 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值