指针作为函数返回值时需要注意的一点是,函数运行结束后会销毁在它内部定义的所有局部数据,包括局部变量、局部数组和形式参数等,函数返回的指针请尽量不要指向这些临时数据,因为函数运行结束后所有的局部变量都销毁了,局部变量的原来的地址可能指向了其他变量。因此,作为指针类型的返回值变量,必须在main函数内定义;这样能保证此变量在main函数的整个生命周期一直存在且有意义。
----------代码如下:
#include
typedef char*
string;
typedef struct
informations{
string
name;
int
age;
}
INFORMATION;
int* fun(int
*a, int *b, int *rt){
*rt = *a +
*b;
return rt
;
}
int
main(void){
int a =3 , b =
5, c =
0;
int *rn = &c ;
//
函数的指针类型返回值必须在主函数中定义,不能在函数内定义临时变量。
//因为函数执行周期结束,临时变量也就销毁了,临时变量的地址也就消失了。
rn = fun(&a,
&b, rn);
printf("rn = %d
\n", *rn);
INFORMATION
zw;
zw.name =
"zw";
zw.age =
3;
printf("name = %s
\n", zw.name);
printf("age = %d
\n", zw.age);
return
0;
}
加载中,请稍候......