天天看点

C语言指针整理3_无类型指针

无类型指针

声明指针时在*前使用void表示类型名称,这种指针叫做无类型指针

这种指针是可以和任意类型的存储区捆绑的。

无法通过指针知道捆绑存储区的类型

无类型指针既不可以直接在前面加

*

也不可以做加减整数的计算

无类型指针必须首先强制类型转换成有类型指针然后才能使用

无类型指针通常作为函数的形式参数使用

#include<stdio.h>
void main()
{
      int num = 0;
      void *p_v =  &num;
      *(int *)p_v = 10;  //强制转换
      //*p_v = 10; 错误的
}
           
//无类型指针
#include<stdio.h>
void print(void *p_v,int type)
{
       if(type == 1)
      {
             printf("%c\n",*(char*)p_v);
      }
       else if(type == 2)
      {
             printf("%d\n",*(int*)p_v);
      }
       else
      {
             printf("%g\n",*(float*)p_v);
      }
}
void main()
{
        int num = 10;
        char ch = 't';
        float fnum = 5.3f;
        print(&ch,1);
        print(&num,2);
        print(&fnum,3); 
}         
           

继续阅读