我的程序一旦在我的代码中到达这个函数就会崩溃。我在函数中打印了数组,这些数组将进入并注释掉所有其他内容,然后
他们被正确地通过了。我搞不懂它为什么会在这里坠毁。
数组是按升序排列的数字。
可能是我的循环或者是语句不对?我想当数组的索引“d”达到attackerArmy[d] = '0'; //represent 0 as defeated时,我可能没有正确地更改它的值?

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

最佳答案

问题
如果attackerArmy[j] >= defenderArmy[i]为真,d将保持未初始化状态,从而在访问attackerArmy[d] = '0';中的值时导致未定义的行为。
可能的修复
声明时初始化d
前任:

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

10-06 07:06