昨天有个同学让我做下面这道有关动态内存的题,做完后就写了这篇小文
#include<iostream>
using namespace std;void GetMemory(char* p,int num)
{
p = (char*)malloc(sizeof(char)*num);
}
int main()
{
char *str=NULL;
GetMemory(str,100);
strcpy(str,"hello");
cout<<str<<endl;
return 0;
}
上面的程序测试后有什么效果?如何修改?
首先上面程序可以编译,但是运行时内存出错。原因是函数传递参数的方式按值传递,将指针str传递给参数时,实际上传递的是str的副本
无论你在GetMemory怎么分配内存,主函数中的str依旧是NULL,因此给NULL指针strcpy一个字符串,必然要报内存错误。
修改1:使用函数返回值
无论如何,GetMemory函数中已经申请了内存,我们只需把他返回给str即可。
#include<iostream>
using namespace std;char* GetMemory(char* p,int num)
{
p = (char*)malloc(sizeof(char)*num);
return p;
}
int main()
{
char *str=NULL;
str = GetMemory(str,100);
strcpy(str,"hello");
cout<<str<<endl;
return 0;
}
修改2:使用引用
引用可以使我们直接去操作参数的本身,而非拷贝
#include<iostream>
using namespace std;void GetMemory(char* &p,int num)
{
p = (char*)malloc(sizeof(char)*num);
}
int main()
{
char *str=NULL;
GetMemory(str,100);
strcpy(str,"hello");
cout<<str<<endl;
return 0;
}
修改3:使用二级指针
虽然传递的是二级指针的副本,但是副本指向的内容和原件是一样,改变副本的内 同样能改变 str
#include<iostream>
using namespace std;void GetMemory(char* *p,int num)
{
*p = (char*)malloc(sizeof(char)*num);
}
int main()
{
char *str=NULL;
GetMemory(&str,100);
strcpy(str,"hello");
cout<<str<<endl;
return 0;
}