指针操作动态内存
因为指针“可变”的特性,常用它操作动态内存。
1,如何通过指针来申请动态内存?
如果函数的参数是一个指针,是否能通过这个参数获取到期望的内存?
void getMemory(char *p, int num){
p = (char*)malloc(sizeof(char) * num);
}
void testGetMem(){
char *str = NULL;
getMemory(str,10);
strcpy(str,"abcdefg");
cout << "test:"<< str <<endl;
}
上面的代码编译不会有问题,但是运行会报:Segmentation fault (core dumped),段错误,也就是strcpy(str,”abcdefg”);出现了非法的地址操作。
所以不能指望通过函数的指针参数,申请动态内存。原因是在getMemory中,编译器总是要为函数的每个参数生成临时副本,指针参数p的副本是_p,编译器是_p=p,函数体中的程序修改_p的内容,会导致p的内容也被改变,这是可以用指针作为输出参数的原因。在上面的代码中,_p申请了新的内存,所以把_p所指向的内存地址改变了,但是p没有任何变化,所以getMemory没能输出任何东西,并且这个函数被执行时,会引起内存泄露,因为没有用free释放内存。
基于前面说的,可以通过指针参数,改变指针的内容,那么如果指针的内容也是一个指针,就应该可以通过这个内容(指针)得到申请的动态内存了,这就是用指向指针的指针作为参数。
void getMemory(char **p, int num){
*p = (char*)malloc(sizeof(char) * num);
}
void testGetMem(){
char *str = NULL;
getMemory(&str,10);
strcpy(str,"abcdefg");
cout << "test:"<< str <<endl;
}
注意如果参数是指向指针的指针,那么在调用getMemory时,传入的&str。
提示一点malloc使用时要做类型转化,因为malloc返回的是void *类型。
还有一种更简单的方法,就是通过返回值传递动态内存:
char *getMemory(int num){
char *p = (char*)malloc(sizeof(char) * num);
return p;
}
void testString(){
char *str = NULL;
str = getMemory(10);
strcpy(str,"abcdefg");
cout << "test:"<< str <<endl;
}
值得注意的是不能用return返回指向栈内存的指针,如下函数就得不到期望的值:
char *getMemory(int num){
char p[] = "abcd";
return p;
}
void testString(){
char *str = NULL;
str = getMemory(10);
//strcpy(str,"abcdefg");
bool ret = (str == NULL)? true:false;
cout << "test,ret="<< ret << ",str="<<str <<endl;
}
结果显示:test,ret=1,str=,
str还是null,因为函数内的变量是在栈内存空间的,这段内存在函数结束后自动消亡。
还没有评论,来说两句吧...