函数指针,指针函数,void *p指针

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ho_Yim

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值