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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ds1130071727/article/details/88671273
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/ds1130071727/article/details/88671273