2019.10.15跨函数使用内存讲解及其示例笔记

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/KaiFcookie/article/details/102577394

跨函数使用内存讲解及其示例
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);
}

猜你喜欢

转载自blog.csdn.net/KaiFcookie/article/details/102577394
今日推荐