跨函数使用内存
函数被调用后,内存会被自动释放(操作系统拿回这块内存的操作权限,但是硬件上的内存还是有垃圾数据的,所以定义变量时都会初始化),这样就不能跨函数使用内存,可以使用malloc()函数来动态分配内存,不调用free()函数不会释放内存,直到所以所以程序执行完后才会释放。
列子:
#include<stdio.h>
#include<malloc.h>
#include <string.h>
struct Student
{
int num;
char name[200];
int age;
};
struct Student * creat_student(void)
{
struct Student *pst = (struct Student *)malloc(sizeof(struct Student));
pst->age = 24;
(*pst).num = 007;
strcpy(pst->name,"xu");
return pst;
}
void show_student(struct Student * p )
{
printf("%d %s %d\n",p->num,p->name,p->age);
}
int main(void)
{
struct Student *st;
st = creat_student();
show_student(st);
return 0;
}