static用法一

时间:2025-04-25 11:05:08
#include "stdafx.h"
#include "string.h"
struct student
{
 int num;
 ];
 char sex;
};
struct student *fun(struct student stu)
{
 struct student *p;
 stu.num = ;
 strcpy_s(stu.name, "abc");
 stu.sex = 'G';
 p = &stu;
 return p;
}
int main()
{
 struct student stu1,*pp;
 stu1.num = ;
 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输出乱码,求解释
 ;
}
进入fun函数时,会创建一个局部变量形参stu,这个形参stu与实参stu1不是一回事,stu只是与stu1 数据一模一样的复制品而已。当fun函数对stu操作结束后返回stu的指针,但因为stu是局部变量,在fun函数结束后会释放掉,由于main函数使 用fun函数返回的指针pp,pp指向了已被释放掉的stu,所以打印时必然输出些乱码。改为static变量