【郝斌数据结构自学笔记】10-11_跨函数使用内存讲解及其示例

来源:互联网 发布:windows 8 whql 编辑:程序博客网 时间:2024/04/28 21:10

10_跨函数使用内存讲解及其示例

CASE 1

int f();

int main(void)

{

         inti=10;

         i=f();

         printf(“i=%d\n”,i);

         for(i=0;i<2000;++i)

                   f();

 

         return0;

}

int f()

{

         intj=20;

         returnj;

}

 

CASE 2

main ()

{

         int*p;

fun(&p);

...

}

int fun (int **q)

{

         ints;        //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

{

         intsid;

         intage;

}

 

struct Student *  CreatStudent(void);

void ShowStudent(struct Student *);

int main(void)

{

         structStudent *ps;

         ps=CreatStudent();

         ShowStudent(ps);

 

         return0;

}

struct Student *  CreatStudent(void)

{

         structStudent *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);

}

11_复习

0 0