关于函数中内存操作

1、传址申请内存问题。

看下面一个例子。

struct complex_t  //复数
{
	int real;  //实数
	int imag;   //虚数
};

int create(complex_t *p, unsigned int n)
{
	p = new complex_t[n];    //申请n个complex
	if(p == NULL)
		return -1;
	else return 0;
}

然后在main函数中调用该函数:

complex_t *comps = NULL;
if(create(comps, 10) < 0)  //调用函数
{
	printf("create failed\n");
	return -1;
}

if(comps == NULL)
{
	cout<<"comps is NULL\n";
	return -1;
}

//其它操作

    create函数的第一个参数,类型时complex_t * 。 然后,在create里面给p分配了一块存储空间。指针做参数,将申请的内存地址返回。
  其实执行之后comps == NULL。
  main函数中调用create函数时,把comps赋值给p。即指针p指向与comps相同的一段存储空间。  但是,在create里面,p=new complex_t[n],使得p又指向了一块新的存储空间。而此时,comps还是指向原来的存储空间。所以,在create里面对p做的更改对comps并没有影响。
  函数create里的参数 complex_t *可以整体类比成int;这样就好理解多了。

  通过上面的分析,不难给出解决办法:

int create(complex_t **p, unsigned int n)
{
	*p = new complex_t[n];    //申请n个complex
	if(p == NULL)
		return -1;
	else return 0;
}

 

 

posted @ 2012-03-14 17:30  陈朋  阅读(267)  评论(0编辑  收藏  举报