1.函数指针数组
本质是一个数组,数组里面的每个元素都是一个指针
返回值类型 (*函数指针变量名【函数指针个数】)(形参列表)
int (*p【10】)(int ,int)
定义了一个函数指针数组,数组中有10个元素p【0】~p【9】,每个元素都是函数指针变量,该函数指针变量指向的函数必须有整型的返回值和两个参数。
#include<stdio.h>
int add(int a,int b);
int sub(int a,int b);
int mul(int a,int b);
int div(int a,int b);
int mod(int a,int b);
int main()
{
int a = 10;
int b = 20;
int c = 30;
int (*p[5])(int ,int ) = {add,sub,mul,div,mod};
// int i;
// for(i=0;i<5;i++)
// {
// printf("%d\n",(*p[i])(a,b));
// }
printf("%d\n",(p[0])((p[0])(a,b),c));
return 0;
}
int add(int a,int b)
{
return a+b;
}
int sub(int a,int b)
{
return a-b;
}
int mul(int a,int b)
{
return a*b;
}
int div(int a,int b)
{
return a/b;
}
int mod(int a,int b)
{
return a%b;
}
2.只读指针变量和只读变量指针
1.只读指针变量
只读指针变量不能被重新赋值,地址不能被修改,值可以修改
定义:类型 *const 变量名
#include<stdio.h>
int main()
{
int a = 20;
int b = 10;
int * const p = &a;
printf("%p\n",p);
printf("%d\n",*p);
*p = 100;
printf("%p\n",p);
printf("%d\n",*p);
printf("%d\n",a);
return 0;
}
2.只读变量指针
只读变量指针,地址可以修改,值不能改变
定义:类型 const *变量名
#include<stdio.h>
int main()
{
int a = 20;
int b = 10;
int const *p = &a;
printf("%d\n",*p);
printf("%p\n",p);
printf("%d\n",a);
p = &b;
printf("%d\n",*p);
printf("%p\n",p);
printf("%d\n",a);
// *p = 200;
// printf("%d\n",*p);
// printf("%p\n",p);
// printf("%d\n",a);
//
return 0;
}
3.特殊指针
1.硬编码赋值给指针
指针变量是指向变量的地址
2.空指针
int *p2 = NULL;
3.野指针
a.指针在定义时未初始化,他会随机指向一个区域,因为任意指针变量(除了staric修饰的指针)它的默认值都是随机的;
b.指针被释放时,没有置空,再用malloc()函数开辟空间时,要检查返回值是否为空,如果为空,则开辟失败,如果不为空,指针指向的是开辟的空间的首地址,指针指向的内存空间再用free()释放后,如果没有对释放后的指针进行置空,就会称为野指针;
4.万能指针 void *(也称空类型指针)
void *指针可以指向任意变量的内存空间
#include<stdio.h>
int main()
{
int a = 10;
char ch = 'a';
float b = 1.2;
void *pp;
pp = &ch;
*((char *)pp) = 'c';
printf("%p\n",pp);
printf("%d\n",*((char *)pp));
pp = &a;
*((int *)pp) = 20;
printf("%p\n",pp);
printf("%d\n",*((int *)pp));
pp = &b;
*((float *)pp) = 3.4;
printf("%p\n",pp);
printf("%.1f\n",*((float *)pp));
return 0;
}