【发布时间】:2013-07-29 23:24:07
【问题描述】:
2d 动态数组的值在循环迭代期间被破坏,例如在循环决策/迭代 16 中,所有值都正确显示,但是当决策/迭代 26 出现时,数组位置 KillRate2 被破坏,即使在迭代没有值被分配给 KillRate 数组。如所附图像所示。
for(int i=0;i<26;i++)
{
for(int j=0;j<9;j++)
{
x[i][j]=0;
y[i][j]=0;
}
}
x[0][0]=0;
x[0][1]=.33;
x[0][2]=.75;
x[1][0]=0;
x[1][1]=.33;
x[1][2]=.75;
x[2][0]=0;
x[2][1]=.33;
x[2][2]=.75;
x[3][0]=0;
x[3][1]=.33;
x[3][2]=.75;
void Display()
{
int StageValue;
int DecisionValue;
double long Minimum;
TreeNodeType *T;
cout<<"**********************@@@@@DISPLAY STARTED@@@@**************************************"<<endl;
for(TreeNodeType *p=Headptr;p!=NULL;p=p->FirstChild)
{
KillRate[3][0]=0;
KillRate[3][1]=.33;
KillRate[3][2]=.75;
DecisionValue=-1;
cout<<"\n\n\n"<<endl;
for(TreeNodeType *q=p;q!=NULL;q=q->Siblings)
{
if(q==Headptr)
{
q->PestPopulation=pestpop;
}
else
{
StageValue=q->stage-1;
DecisionValue=DecisionValue+1;
if(DecisionValue==(noOfDecisions))
{
DecisionValue=0;
}
double C1=KillRate[StageValue][DecisionValue];
double K1=Cost[StageValue][DecisionValue];
cout<<"Stage Value/Decision Value"<<StageValue<<"/"<<DecisionValue<<endl;
q->PestPopulation=q->Parent->PestPopulation;
long double a=(1 - C1);
long double b=(PI)*(q->PestPopulation);
long double c=(K1)*(this->area);
for(int i=0;i<26;i++)
{
for(int j=0;j<9;j++)
{
cout<<"KillRate:"<<KillRate[i][j]<<" ";//THIS IS THE PLACE WHERE THROUGH ITERATION ARRAY IS BEING DISPLAYED
}
cout<<endl;
}
cout<<a<<"*"<<b<<"+"<<c<<endl;
q->Loss= (a*b)+ c;
TotalLoss[q->stage-1][q->Decision-1]=q->Loss + q->Parent->Loss;
q->PestPopulation=(1-C1)*(q->PestPopulation)*(this->growthrate);
cout<<"Stage= "<<q->stage<<", Decision= "<<q->Decision<<", PestPop="<<q->PestPopulation<<", Loss ="<<q->Loss<<endl<<endl;
if(q->Loss>Minimum)
{
Minimum=q->Loss;
T=q->Parent;
}
}
}
}
while(T!=Headptr)
{
cout<<"Decision Sequence :"<<T->stage<<" / "<<T->Decision<<endl;
T=T->Parent;
DecisionSequence[T->stage]=T->Decision;
cout<<"Decision Sequence :"<<T->Decision<<" ,\t ";
}
cout<<"**********************@@@@@DISPLAY ENDED@@@@**************************************"<<endl;
}
【问题讨论】:
-
你不喜欢最小的完整示例,是吗?
-
KillRate 多维数组仅分配给 3 个值。您要求显示 9*26 不同索引的值。你是如何初始化 KillRate 数组的?
-
@sgun 我只想保留 3 个值,其他值初始化为零,程序只是根据要求使用这些值。我有这样的初始化数组: KillRate=new double*[26]; for(int i=0;i
-
我能想到两种方法。使用
calloc或memset。你用过这些吗? -
这是c++而不是c。
标签: c++ memory-management memory-leaks multidimensional-array