在C

时间:2016-03-02 04:47:28

标签: c arrays loops

我的程序在代码中达到此功能后崩溃。我在正在进入的函数中打印了数组,并注释掉了其他所有内容 他们正确地通过了。我无法弄清楚为什么它会在这里崩溃。

数组是按升序排列的数字。
也许我的循环或if语句不正确?我想也许当我到达attackerArmy[d] = '0'; //represent 0 as defeated时,我没有正确地更改索引“d”中数组中的值?

long int defeatedArmies(long int* attackerArmy, long int* defenderArmy, long int size){

    long int i,j,defeated = 0,d;

    for(i=0;i<size;i++){
        for(j=0;j<size;j++){

        //loop for the highest attack value that is lower than defender
            if(attackerArmy[j] < defenderArmy[i])
                d = j; // save the index where it is highest

            if(attackerArmy[j] > defenderArmy[i])
            //no point in checking unnecessary values
                break;
        }
        attackerArmy[d] = '0'; //represent 0 as defeated
    }

    for(i=0;i<size;i++){
        if(attackerArmy[i] == 0) //count how many defeated armies happened
            defeated++;
    }
return defeated;
}

1 个答案:

答案 0 :(得分:3)

<强>问题
如果attackerArmy[j] >= defenderArmy[i]为真,则d保持未初始化状态,导致在attackerArmy[d] = '0';中访问其值时出现未定义的行为。

可能的解决方法
在声明时初始化d

<强>例如:

long int d = -1L;
...
if(d != -1L) attackerArmy[d] = '0';