在if循环外访问动态创建的数组

时间:2014-09-26 16:35:50

标签: c++ arrays

我的情况如下

class A
{
double * array

void function1();

};

void A :: function1 ()
{
      if (condition)
      {
        array1= new double[n];
        fill the array1
      }

      **how to access the array1 here ?**
}

2 个答案:

答案 0 :(得分:1)

if

之外定义数组
void A :: function1 ()

{ 
 float *array1= null;
if (condition) { array1= new double[n]; fill the array1 }
cout<<array1[0];

}

答案 1 :(得分:0)

您无法访问块外的本地变量。您动态分配了内存。那样就好。但问题是你使用名为&#39; array1&#39;的局部变量来指向内存。在一个街区内。因此,一旦您走出街区,您就无法访问该变量。所以它是一个内存泄漏,因为一旦你走出阻止,你就无法释放内存。

为了不泄漏内存,您可以使用Abhi发布的代码。

相关问题