一、字符指针变量(char*)
1.%s打印字符串时,需要提供一个地址
2.字符指针指向一个字符串:字符指针里面存放字符串首字符地址
int main()
{
const char* pstr = "hello.";//把首字符h的地址放到pstr里面
printf("%s\n", pstr); //打印hello
return 0;
}
《剑指offer》笔试题:求程序输出结果
#include <stdio.h>
int main()
{
char str1[] = "hello bit.";
char str2[] = "hello bit.";
const char *str3 = "hello bit.";
const char *str4 = "hello bit.";
if(str1 ==str2)
printf("str1 and str2 are the same\n");
else
printf("str1 and str2 are not the same\n");
if(str3 ==str4)
printf("str3 and str4 are the same\n");
else
printf("str3 and str4 are not the same\n");
return 0;
}
解析:相同的常量字符串(不可被修改)没必要存两份,因此只占一块内存空间(3和4指向的地址相同);而两个数组虽然存储的内容相同,但是开辟了两块不同的内存空间。
二、数组指针变量
1.数组指针:存放数组的地址,是一个能够指向数组的指针变量
类比:整型指针变量(int* pointer)存放整型变量的地址,能够指向整型数据
浮点型指针变量(float* pointer)存放浮点型变量的地址,能够指向浮点型数据
那么数组指针存放的就应该是数组的地址
(1)数组指针的写法
int *p1[10];
int (*p2)[10];
(2)[]的优先级高于*,所以必须加()保证p先和*结合
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/50af13431980408b82ff1aa17c25429c.png
2.数组指针变量初始化的方法
int(*p)[10] = &arr;
p先和*结合,说明p是一个指针变量,且指向的是一个大小为10个int数据的数组,所以叫做数组指针
三、二维数组传参的本质
1.二维数组的元素:一维数组==>二维数组的首元素:第一行这个一维数组
2.二维数组的数组名表示首元素的地址:即第一行这个一维数组的地址
#include <stdio.h>
void test(int (*p)[5], int r, int c)
{
int i = 0; int j = 0;
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)
{
printf("%d ", *(*(p+i)+j));
}
printf("\n");
}
}
int main()
{
int arr[3][5] = {{1,2,3,4,5}, {2,3,4,5,6},{3,4,5,6,7}};
test(arr, 3, 5);
return 0;
}
四、函数指针变量
1.函数指针变量的创建
(1)函数指针:是指向函数的指针,可以存放函数的地址,未来可以通过地址调用函数
(2)函数名和&函数名没有区别
(3)具体代码举例
//代码1
void test()
{
printf("hehe\n");
}
void (*pf1)() = &test;
void (*pf2)()= test;
//代码2
int Add(int x, int y)
{
return x+y;
}
int(*pf3)(int, int) = Add;
int(*pf3)(int x, int y) = &Add;//x和y写上或者省略都是可以的
2.函数指针变量的使用
#include <stdio.h>
int Add(int x, int y)
{
return x+y;
}
int main()
{
int(*pf3)(int, int) = Add;
printf("%d\n", (*pf3)(2, 3));
printf("%d\n", pf3(3, 5));
return 0;
}
五、函数指针数组
1.把函数的地址存放到数组当中,这个数组就是函数指针数组
2.定义方式:int (*parr1[3])()={fun1,fun2,fun3};
六、转移表
1.函数指针数组的应用:转移表(像一个跳板一样,跳转到各个函数)
//利用函数指针数组实现计算器
#include <stdio.h>
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 main()
{
int x, y;
int input = 1;
int ret = 0;
int(*p[5])(int x, int y) = { 0, add, sub, mul, div }; //转移表
do
{
printf("*************************\n");
printf(" 1:add 2:sub \n");
printf(" 3:mul 4:div \n");
printf(" 0:exit \n");
printf("*************************\n");
printf( "请选择:" );
scanf("%d", &input);
if ((input <= 4 && input >= 1))
{
printf( "输⼊操作数:" );
scanf( "%d %d", &x, &y);
ret = (*p[input])(x, y); //此处便是转移表的体现,通过一个函数指针以及input的值,实现对于指定函数的调用,起到了**跳转的效果**
printf( "ret = %d\n", ret);
}
else if(input == 0)
{
printf("退出计算器\n");
}
else
{
printf( "输⼊有误\n" );
}
}while (input);
return 0;
}