传递动态内存

来源:互联网 发布:icloud备份微信数据 编辑:程序博客网 时间:2024/05/20 22:27

参考《程序员面试宝典》

例1 下面的程序运行会有什么结果?

#include <iostream>void GetMemory(char *p, int num){p = (char *) malloc (sizeof(char)*num);};int main(){char *str = NULL;GetMemory(str, 100);strcpy(str, "hello");return 0;}

运行该程序会崩溃,因为GetMemory在这里不能传递动态内存,Test函数中的str一直都是NULL。该例中,void GetMemory(char *p, int num)中的*p实际上是主函数中的str的一个副本,编译器总是要为函数的每个参数制作临时副本。p申请了新的内存,只是把p所指的内存地址改变了,但是str丝毫未变,str并没有指向p所申请的那段内存。

可以做如下修改:

#include <iostream>void GetMemory(char **p, int num){*p = (char *) malloc (sizeof(char)*num);};int main(){char *str = NULL;GetMemory(&str, 100);strcpy(str, "hello");return 0;}
或者使用函数返回值来传递动态内存

#include <iostream>char *GetMemory(char *p, int num){p = (char *) malloc (sizeof(char)*num);};int main(){char *str = NULL;str = GetMemory(str, 100);strcpy(str, "hello");return 0;}
为了加深理解指针p,&p,*p,可以再看看这个例子:

#include <cstdlib>#include <iostream>using namespace std;int main(int argc, char *argv[]){int *p = NULL;cout<<"p: "<<p<<endl;cout<<"&p: "<<&p<<endl<<endl;int b,c,a;a = 5;p = &a;cout<<"&a: "<<&a<<endl;cout<<"p: "<<p<<endl;cout<<"&p: "<<&p<<endl;cout<<"*p: "<<*p<<endl<<endl;p++;cout<<"p: "<<p<<endl;cout<<"&p: "<<&p<<endl;    system("PAUSE");    return EXIT_SUCCESS;}

运行结果:

p: 0&p: 0x22ff44&a: 0x22ff38p: 0x22ff38&p: 0x22ff44*p: 5p: 0x22ff3c&p: 0x22ff44

指针变量p涉及到两个地址:指针变量p用来指向对象的地址,但是初始化为NULL时,不指向任何变量,所以cout<<p会输出0,当p = &a后,p的内容变为变量a的地址,所以cout<<p与cout<<&a的结果一样;&p是变量p的地址,该地址永远不会改变(进行p++操作时,改变的是p所指向地址(p的内容),从运行结果可以看到,p内容加4,因为int占4字节,但是p本身的地址是不会改变的)。




原创粉丝点击