1. 字符指针变量
int main()
{
const char* pstr = "hello bit.";
printf("%s\n", pstr);
return 0;
}
代码 const char* pstr = “hello bit.”
本质是把字符串 hello bit. 首字符的地址放到了pstr中。
#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 same\n");
else
printf("str1 and str2 are not same\n");
if(str3 ==str4)
printf("str3 and str4 are same\n");
else
printf("str3 and str4 are not same\n");
return 0;
}
常量字符串hello bit. 存放在内存的只读区域
str1和str2是两个字符数组,存放字符串的首地址,二者地址不同,所以不一样
*str3和*str4 因为是指针,指向常量字符串hello bit.,每个常量字符串在内存中只有一份,二者指向的地方一样,地址一样,所以二者相同
2. 数组指针变量
int (*p)[10];
[]的优先级要高于*号的,所以必须加上()来保证p先和*结合。
如果要存放个数组的地址,就得存放在数组指针变量中,如下:
int(*p)[10] = &arr;
3. 二维数组传参的本质
首先我们再次理解⼀下二维数组,二维数组其实可以看做是每个元素是一维数组的数组,也就是二维数组的每个元素是一个一维数组。那么二维数组的首元素就是第一行,是个一维数组。
int arr[3][5] = {{1,2,3,4,5}, {2,3,4,5,6},{3,4,5,6,7}};
上面的例子,第一行的一维数组的类型就是 int (*)[5] ,所以第一行的地址的类型就是数组指针类型 int(*)[5] 。那就意味着二维数组传参本质上也是传递了地址,传递的是第一行这个⼀维数组的地址,那么形参也是可以写成指针形式的。
void test(int (*p)[5], int r, int c);
void test(int a[3][5], int r, int c);
4. 函数指针变量
函数指针变量是用来存放函数地址的,未来通过地址能够调用函数的。
#include <stdio.h>
void test()
{
printf("hehe\n");
}
int main()
{
printf("test: %p\n", test);
printf("&test: %p\n", &test);
return 0;
}
函数是有地址的,函数名就是函数的地址,当然也可以通过 &函数名 的方式获得函数的地址。
如果我们要将函数的地址存放起来,就得创建函数指针变量
void test()
{
printf("hehe\n");
}
void (*pf1)() = &test;
void (*pf2)()= test;
int Add(int x, int y)
{
return x+y;
}
int(*pf3)(int, int) = Add;
int(*pf3)(int x, int y) = &Add;//x和y写上或者省略都是可以的
#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;
}
5. 函数指针数组
要把函数的地址存到一个数组中,那这个数组就叫函数指针数组
int (*parr1[3])();
parr1 先和 [] 结合,说明 parr1是数组,数组的内容是 int (*)() 类型的函数指针。
6. 转移表
#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);
printf( "ret = %d\n", ret);
}
else if(input == 0)
{
printf("退出计算器\n");
}
else
{
printf( "输⼊有误\n" );
}
}while (input);
return 0;
}