#include "stdio.h"
/******************************************************/
//函数指针
void (*p)(void); //它可以访问任何一个void Function(void)类型的函数
void hello(void)
{
printf("hello\n");
}
void print(void)
{
printf("print\n");
}
/*********************************************************************/
/*********************************************************************/
int* (*f)(int,int); //返回一个地址
int c;
int* add(int a,int b) //指针函数:指向函数指针的指针,本质是一个指针
{
//在此不能声明int c;
c = a+b;
printf("add:");
return &c; //返回c的地址
}
int* sub(int m,int n)
{
c = m - n;
printf("sub:");
return &c; //返回c的地址
}
/*********************************************************************/
int main()
{
p = hello;
(*p)(); //使用函数指针调用hello()函数
p = print;
(*p)(); //使用函数指针调用print()函数
f = &add; //等价于f = add;
printf("%d\n",*(*f)(2,3)); //两个函数都返回一个地址,所以要取两次值才能运行最终的函数
f = sub; //等价于f = ⊂
printf("%d\n",*(*f)(9,1));
return 0;
}
关于void *p:
#include "stdio.h"
typedef struct student
{
char name;
int age;
int num;
void *p;
float f;
}student;
//void (*p)()是一个指向函数的指针,表示是一个指向函数入口的指地变量,该函数的返回类型是void类型
int main(void)
{
char str = 'a';
void *p; //可以指向任何类型
printf("Byte test:\n");
/*printf("char:%d\n",sizeof(char)); //char:1Byte
printf("short:%d\n",sizeof(short)); //short:2Byte
printf("int:%d\n",sizeof(int)); //int:4Byte
printf("long:%d\n",sizeof(long)); //long:4Byte
printf("float:%d\n",sizeof(float)); //float:4Byte
printf("double:%d\n",sizeof(double)); //double:8Byte
printf("student:%d\n",sizeof(student)); */ //结构体类型
printf("void *p Specifies the size of the p address:%d\n",sizeof(p)); //地址为8Byte(64bit)
printf("*p sizeof:%d\n",sizeof(*p));
p = &str;
//printf("*p:%c",*p); //将会报错
printf("After p=&str is executed, the sizeof p is:%d\n",sizeof(p));
printf("The size of the *p:%d\n",sizeof(*p));
printf("Prints the actual value of the pointer,*((char*)p):%c\n",*((char*)p)); //将指针p强制转换为(char*)指针类型
return 0;
}