函数指针、指针函数、指针数组、数组指针

2023-06-20,

函数指针是一个指向函数的指针,即它是一个指针变量,只不过这个指针指向一个函数。

函数指针的定义:

 返回值类型 (*指针变量名)(形参列表);int (*fun)(int a,int b);

注意:

1)声明函数指针时必须和要指向的函数返回值以及参数类型保持一致,否则会出错。

2)指向函数的指针没有++和--运算。

3)函数指针指向的函数必须是被定义了并且分配了内存的,否则它将指向一个空地址。会编译不通过。  

#include<stdio.h>
#include<stdlib.h>
int max(int a,int b)
{
	return a>b? a:b;
}
int main()
{
	int (*fun)(int,int);
	fun = max;
	int ret = (*fun)(10,8);
	printf("%d\n",ret);
	system("pause");
	return 0;
}
#include<stdio.h>
#include<stdlib.h>
typedef void (*fun)();
void f1()
{
	printf("this is f1\n");
}
void f2()
{
	printf("this is f2\n");
}
int main()
{
	fun f = f1;
	f();
	f = f2;
	f();
	system("pause");
	return 0;
}
//函数指针被当做参数使用
int max(int a,int b)
{
	return a>b? a:b;
}
int add(int (*f)(int a,int b),int x)
{
	return (*f)(7,8)+x;
}
int main()
{
	int (*fun)(int,int);
	fun = max;
	int ret = add(fun,10);
	printf("%d\n",ret);
	system("pause");
	return 0;
}

指针函数

指针函数是一个函数,定义为:返回类型 *函数名(形参列表);int *f(a,b);返回值是一个指针。

int *fun(int *a)
{
	return a+3;
}
int main()
{
	int arr[] = {1,2,3,4,5,6,7,8,9,10}; 
	int *ret = fun(arr);
	printf("%d ",*ret);
	system("pause");
	return 0;
}

指针数组:

指针数组为一数组,只不过数组中每个元素都是一个指针。

定义为:类型 *变量名[大小]; int *array[10];

#include<stdio.h>
#include<stdlib.h>
#define _SIZE_ 3
int main()
{
	char *arr[_SIZE_]={"how","are","you"};
	for(int i=0;i<_SIZE_;++i)
	{
		printf("%s ",arr[i]);
	}
	system("pause");
	return 0;
}

数组指针:

数组指针是一个指针,是一个指向该数组的指针,相当于一个二级指针。

定义为:类型 (*变量名)[数组大小];int (*arr)[3];

void print(char (*s)[5],int lenth)
{
	for(int i =0;i<lenth;i++)
	{
		printf("%s ",s[i]);
	}
}
int main()
{
	char arr[][5]={"how","are","you"};
	int size = sizeof(arr)/sizeof(arr[0]);
	print(arr,size);
	system("pause");
	return 0;
}
int main()
{
	char arr[][5]={"how","are","you"};
	int size = sizeof(arr)/sizeof(arr[0]);
	char (*s)[5];
	s = arr;
	for(int i=0;i<size;i++)
	{
		printf("%s ",s[i]);
	}
	system("pause");
	return 0;
}

《函数指针、指针函数、指针数组、数组指针.doc》

下载本文的Word格式文档,以方便收藏与打印。