解决动态内存传递不能传递的3种方法

// 动态内存传递.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;
/*动态内存传递
1 在C中,使用指向指针的指针解决这个问题
2 在C++中,使用传递指针的引用
3 使用函数返回值来传递动态内存
*/

void GetMemory1(char **p,int num){
*p=(char*)malloc(sizeof(char)*num);

}

void GetMemory2(char *&p,int num){

	p=(char*)malloc(sizeof(char)*num);
}

char* GetMemory3(int num){
char *p=(char*)malloc(sizeof(char)*num);
 return p;
}

int _tmain(int argc, _TCHAR* argv[])
{
	char *str1=NULL;
	char* str2=NULL;
	char *str3=NULL;
	char *str4=NULL;

	GetMemory1(&str1,20);
	GetMemory2(str2,40);
	str3=GetMemory3(20);
	strcpy(str1,"GetMemory1");
	strcpy(str2,"GetMemory2");
	strcpy(str3,"GetMemory3");
	cout<<"str1="<<str1<<endl;
	cout<<"str2="<<str2<<endl;
	cout<<"str3="<<str3<<endl;
	cout<<"str1==null?"<<(str4==NULL?"yes":"no")<<endl;
	free(str1); //释放内存,并把指针赋为NULL
	free(str2);
	free(str3);
	str1=NULL;
	str2=NULL;
	str3=NULL;
	getchar();
	return 0;
}

 

在上面的代码中:

GetMemory1()函数采用二维指针作参数传递。

GetMemory2()函数采用指针的引用作参数传递。

GetMemory1()函数采用返回堆内存指针的方式传递。

三种方式起到了相同的作用。


 
 
 




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值