2d动态数组的值在循环迭代期间被破坏,例如在循环决策/迭代16中,所有值都正确显示但是当来到Decision / iteration 26时,阵列位置KillRate 2即使在迭代没有赋值给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;
}
答案 0 :(得分:2)
KillRate = new double*[26];
for(int i=0;i<26;i++) { KillRate[i] = new double[9];}
此分配仅分配内存。因此未分配的地址将具有任意值。 c ++解决方案将是:
for(int i=0;i<26;i++){
for(int j=0;j<9;j++){
KillRate[i][j] = 0;
}
}
或更快的c解决方案;
使用calloc
或memset
答案 1 :(得分:1)
这可能是因为内存管理问题我遇到了同样的问题,我通过将每个对象变成指针并通过新的对象* KillRate = new object分配内存来解决这个问题;
希望这可能会有所帮助