指针函数 和 函数指针数组 的简单用法

例如: 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//指针函数 ---     一个函数,它的返回值是指针
char * fun1(void)
{
	char p[] = "hello world";
	return p;   //不能返回栈中的地址,因为函数执行结束时,栈的空间就释放了
}
char * fun2(void)
{
	static char p[] = "hello world"; //可以返回.data或.bss中的地址,返回后该空间是可读可写
	return p;
}
char * fun3(void)
{
	char *p = "hello world";

	return p;   //可以返回.rodata中的地址,返回后该空间中的数据不能修改,为只读数据
}
char * fun4(void) //
{
	char *p = (char*)malloc(20);
	strcpy(p,"hello world");
	return p;  //可以返回.heap中的地址,返回后该空间是可读可写
}
int main(void)
{
	char *str = NULL;
	str = fun4();    ///可以使用此处尝试
	printf("str = %s\n",str);
	*str = 'H';     // 把'h'更改为'H'
	printf("str = %s\n",str);
	strcpy(str,"farsight");
	printf("str = %s\n",str);
	return 0;
}

函数指针数组的使用

元素类型为函数指针类型的数组称为函数指针数组

例如: 
int  (*p[5])(int,int);    //p为函数指针数组,有5个元素,每个元素为函数指针,函数指针指向的函数有两个int型参数,有一个int型返回值

例如: 
int  fun1(int a,int b)
{
	return a + b;
}
int  fun2(int a,int b)
{
	return a - b;
}

int  fun3(int a,int b)
{
	return a * b;
}
int  fun4(int a,int b)
{
	return a / b;
}
int main(void)
{
	int a,b;

	printf("请输入a和b:");
	scanf("%d%d",&a,&b);
/*
	printf("%d + %d = %d\n",a,b,fun1(a,b));
	printf("%d - %d = %d\n",a,b,fun2(a,b));
	printf("%d * %d = %d\n",a,b,fun3(a,b));
	printf("%d / %d = %d\n",a,b,fun4(a,b));
*/
	int (*arr[4])(int,int) = {fun1,fun2,fun3,fun4};  //定义函数指针数组,保存4个函数的入口地址
	int i;
	char str[] = "+-*/";
		
	for(i = 0 ; i < 4; i++)    //通过数组循环调用不同的函数
		printf("%d %c %d = %d\n",a,str[i],b,arr[i](a,b));        

	return 0;
}
posted @ 2022-04-20 20:52  孤走  阅读(52)  评论(0编辑  收藏  举报