跨函数使用内存讲解及其示例
CASE 1
#include<stdio.h>
int f();
int main(void)
{
int i=10;
i=f();
printf(“i=%d\n”,i);
for(i=0;i<2000;++i)
f();
return 0;
}
int f()
{
int j=20;
return j;
}
CASE 2
main ()
{
int *p;
fun(&p);
...
}
int fun (int **q)
{
int s; //s为局部变量。调用完毕后s就没有了,最终p没有指向一个合法的整型单元
*q=&s;
}
CASE 3
main()
{
int *p;
fun(&p);
...
}
int fun(int **q)
{
*q=(int *)malloc(4); **//返回4个字节,只取第1个字节地址赋给*q,*q==p。执行完后,因为没有free(),内存没有释放。如果没有free(),整个程序彻底终止时才能释放**
}
程序内部类定义方法
A aa=new A();
A *pa=(A*)malloc(sizeof(A));
CASE 4
#include<stdio.h>
#include<malloc.h>
struct Student
{
int sid;
int age;
}
struct Student * CreatStudent(void);
void ShowStudent(struct Student *);
int main(void)
{
struct Student *ps;
ps=CreatStudent();
ShowStudent(ps);
return 0;
}
struct Student * CreatStudent(void)
{
struct Student *P=(struct Student *)malloc(sizeof(struct Student));
p->sid=99;
p->age=88;
return p;
}
void ShowStudent(struct Student *pst)
{
printf(“%d %d\n”,pst->sid,pst->age);
}