【问题标题】:This piece of code executes fine once and gives segmentation fault the other time这段代码一次执行良好,另一次出现分段错误
【发布时间】:2020-06-08 11:35:17
【问题描述】:

我有宝石对象 gems[10][10],它有一个属性颜色。我想在具有相同颜色的列中获得三个或更多连续的宝石,并改变它们的颜色。下面的代码一次运行良好,而另一次出现分段错误。是什么导致随机运行中的分段错误。

    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;
}

【问题讨论】:

标签: c++ arrays loops opengl


【解决方案1】:
 while(gems[a][i].getColor()==gems[j][i].getColor() && a<10){

a 达到 10 的值时,这里。 gems[10]a&lt;10 比较之前被评估。由于这超出了数组的大小,因此会导致未定义的行为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-19
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多