C语言允许函数的返回值是指针类型,我们把这个函数称为指针函数,举例:
#include<stdio.h>
int *compute(int *a,int *b)
{
if(*a > *b)
return a;
else
return b;
}
int main( int argc , char *argv[] )
{
int a = 1;
int b = 2;
int *p = compute(&a,&b);
printf("%d\n",*p);
return 0;
}
程序的运行结果:
[wanghe@localhost ~]$ ./test.exe
2
用指针作为函数返回值时需要注意的一点是,函数运行结束后会销毁在它内部定义的所有局部数据,包括局部变量、局部数组和形式参数,函数返回的指针请尽量不要指向这些数据,C语言没有任何机制来保证这些数据会一直有效,它们在后续使用过程中可能会引发运行时错误。请看下面的例子:
#include<stdio.h>
int *compute()
{
int n = 100;
return &n;
}
int main( int argc , char *argv[] )
{
int *p = compute();
//printf("函数返回值是%d\n",*p);
int n = *p;
printf("%d\n",n);
return 0;
}
输出结果:
[wanghe@localhost ~]$ gcc -g -o test.exe test.c
test.c: 在函数‘compute’中:
test.c:6:2: 警告:函数返回局部变量的地址 [-Wreturn-local-addr]
return &n;
^
[wanghe@localhost ~]$ ./test.exe
100
可以看出系统提示警告,但是结果还是100,如果把注释掉的语句加上,再看结果:
[wanghe@localhost ~]$ gcc -g -o test.exe test.c
test.c: 在函数‘compute’中:
test.c:6:2: 警告:函数返回局部变量的地址 [-Wreturn-local-addr]
return &n;
^
[wanghe@localhost ~]$ ./test.exe
函数返回值是100
32729
[wanghe@localhost ~]$
可以看出值不是100了,原因是虽然指针函数原则上是被销毁了,实际上是系统放弃了对函数所占内存区域的使用权,如果没有新的程序占据内存,值是不会改变的,所以添加一条语句结果就变了,就是因为原来的内存被修改了。