指针函数的概念
本质是函数,函数返回值是指针。类比着指针数组。指针数组:本质是数组,数组中每个元素是指针。指针数组定义格式:数据类型 *数组名[元素个数];
定义格式
数据类型 *函数名(参数列表)
{
函数体;
return 地址; //当失败时一般返回NULL
}
错误案例
案例1:
#include <stdio.h>
char *fun()
{
char buf[32] = "hello";
return buf;
}
int main(int argc, char const *argv[])
{
char *p = fun();
printf("%s\n", p);
return 0;
}
主函数里的*p指向的是空输不错想要的hello的结果
案例2:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void create_space(char *p) //p=NULL
{
p = (char *)malloc(32); //改变p的指向,让p指向开辟的堆区
if (NULL == p)
printf("malloc err");
strcpy(p, "hello");
}
int main(int argc, char const *argv[])
{
char *q = NULL;
create_space(q); //函数调用后,q依然指向NULL
//因为p和 q是两个空间,改变函数内的p是不影响函数外的q
printf("%s\n", q);
return 0;
}
报段错误:因为q指向NULL, 函数内改变形参p的指向不会影响到q,q还是指向NULL。
可以通过二级指针进行改错
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void create_space(char **p) //p=&q
{
*p = (char *)malloc(32); //*p = *&q = q
if (NULL == *p)
printf("malloc err");
strcpy(*p, "hello");
}
int main(int argc, char const *argv[])
{
char *q = NULL;
create_space(&q);
//调用函数后,q指向函数内开辟的堆区。因为函数内通过传递q的地址找到q, 让q真的指向开辟的堆区了。
printf("%s\n", q);
return 0;
}
案例3:
#include <stdio.h>
void fun(int arr[5]) //arr类型是int *
{
arr[0] = 100;
printf("%ld\n", sizeof(arr));
}
int main(int argc, char const *argv[])
{
int a[5] = {1, 2, 3, 4, 5};
fun(a);
printf("%d\n", a[0]);
return 0;
}
传递数组的形式是为了让用户知道要传递的是一个数组,但本质还是传递数组的首地址,也就是传递指针。