简体   繁体   English

这段代码一次执行良好,另一次出现分段错误

[英]This piece of code executes fine once and gives segmentation fault the other time

I have gems objects gems[10][10], which have an attribute color.我有宝石对象 gems[10][10],它有一个属性颜色。 I want to get three or more consecutive gems in a column having same color, and change thier color.我想在具有相同颜色的列中获得三个或更多连续的宝石,并改变它们的颜色。 The code below works just fine once while gives segmentation fault the other time.下面的代码一次运行良好,而另一次出现分段错误。 What cause the segmentation fault in random runs.是什么导致随机运行中的分段错误。

    bool findMatch(){
        for(int i=0;i<10;++i){      // To check ForVertical matchces
            for(int j=1;j<10;++j){
                int count=0;
                int a=0;
                if(gems[j][i].getColor()==gems[j-1][i].getColor()){
                    a=j;
                    count++;
                    while(gems[a][i].getColor()==gems[j][i].getColor() && a<10){
                        count++;
                        a++;
                    }
                }
             if(count>=3){
                 for(int x=j-1, itr=0;itr<count;++itr,++x){
                     gems[x][i].setColor(7);
                 }
                    glutPostRedisplay();
                 for(int x=j-1, itr=0;itr<count;++x,++loop){
                     gems[x][i].setColor(GetRandInRange(0,7));
                 };
                 return true;
             }
            }
        }
return false;
}
 while(gems[a][i].getColor()==gems[j][i].getColor() && a<10){

When a reaches the value of 10, here.a达到 10 的值时,这里。 gems[10] gets evaluated before the a<10 comparison. gems[10]a<10比较之前被评估。 Since this exceeds the size of the array, this results in undefined behavior.由于这超出了数组的大小,因此会导致未定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM