首先在前面我们就讲解了指针的基本的一些基本的概念以及一些指针相关的定义,这篇我们就来讲解讲解一下指针中的一些陷进。
指针其实不难理解,难理解是指针指向的内存个一些指针的sizeof()的运算。
陷进一:指针数组和数组指针
例如下面的代码
#include <stdio.h>
#include <stdlib.h>
int main(){
char arr[] = "abcdef";
system("pause");
return 0;
}
我们进行如下两个操作的时候
#include <stdio.h>
#include <stdlib.h>
int main(){
char arr[] = "abcdef";
printf("%p\n", arr);
printf("%p\n", &arr);
system("pause");
return 0;
}
得到的结果是一样的,此时我们要明白arr是数组名,指向数组的首元素的地址,但是&arr是指向整个数组元素的,但是两个本质上都是指针,只是指向的内容不是一样的。这就是数组指针。
下面我们呢看如下的代码
#include <stdio.h>
#include <stdlib.h>
int main(){
char arr[] = "abcdef";
char arr1[] = "abcdef";
char* p[] = {arr,arr1};
system("pause");
return 0;
}
此时的p就是一个数组,这个数组特殊就在于每个元素都是一个数组指针。实质上就是一个数组。这就是我们所说的指针数组和数组指针。
陷进二:数组作为参数时传参
在我们一位数组作为参数时传递的就是一个地址,在c语言中数组名就是一个指针,或者一个一维数组。
#include <stdio.h>
#include <stdlib.h>
void test(char* p){
}
int main(){
char arr[] = "abcdef";
test(arr);
system("pause");
return 0;
}
此时这样传参时可以的。但是也可以更换为void test(char []p),同样也是可以正确的传参。
一位数组传参并没有什么陷进,但是对于二维数组的时候我们就需要注意一些小细节。
在传递参数的时候可以省略前面的数字,但是后面的数字我们必须写入,数字的大小无关紧要。
#include <stdio.h>
#include <stdlib.h>
void test(int arr[][100]){
}
int main(){
int arr[][5] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
test(arr);
system("pause");
return 0;
}
此时我们写入100也是无关紧要的。
函数指针
这是我们最重要的,是我们最常用的一个知识点,但是也同样是要注意的get
#include <stdio.h>
#include <stdlib.h>
void test(){
}
int main() {
printf("%p\n", test);
printf("%p\n", &test);
system("pause");
return 0; }
这两个结果是相同的,我们可以定义一个函数指针将这个地址存储起来,以便我们以后去使用,这样是可以节省一些出入栈消耗的。
#include <stdio.h>
#include <stdlib.h>
void test(){
printf("hehe\n");
}
int main(){
void(*p)() = test;
p();
system("pause");
return 0;
}
我们可以去正常去调用test函数。
函数指针数组,这是我们的重点。
int(*p[4])(int x, int y) = { add, sub, mul, div };
add,sub,mul,div都是函数名。称为转移表
在调用的时候可以直接p[0](3,4),这就是转移表的运用。