标签:
#include "stdafx.h" #include "string.h" struct student { int num; char name[20]; char sex; }; struct student *fun(struct student stu) { struct student *p; stu.num = 10; strcpy_s(stu.name, "abc"); stu.sex = ‘G‘; p = &stu; return p; } int main() { struct student stu1,*pp; stu1.num = 10; strcpy_s(stu1.name, "def"); stu1.sex = ‘M‘; printf("num=%d name=%s sex=%c\n",stu1.num,stu1.name,stu1.sex); pp = fun(stu1); printf("num=%d name=%s sex=%c\n", (*pp).num, (*pp).name, (*pp).sex);//name输出乱码,求解释 return 0; } 进入fun函数时,会创建一个局部变量形参stu,这个形参stu与实参stu1不是一回事,stu只是与stu1 数据一模一样的复制品而已。当fun函数对stu操作结束后返回stu的指针,但因为stu是局部变量,在fun函数结束后会释放掉,由于main函数使 用fun函数返回的指针pp,pp指向了已被释放掉的stu,所以打印时必然输出些乱码。改为static变量
标签:
原文地址:http://www.cnblogs.com/x113/p/4505880.html