Hispazn
Hispazn

Reputation: 103

Changing the value of elements in an array in C

My program crashes once it reaches this function in my code. I printed the arrays in the function that are going in and commented out everything else and they are getting passed correctly. I can't figure out why it crashes here.

The arrays are numbers in ascending order.
Maybe my loops or if statements are not right? I think maybe I'm not correctly changing the value in the array at index "d" when it reaches 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;
}

Upvotes: 1

Views: 369

Answers (1)

Mohit Jain
Mohit Jain

Reputation: 30489

Problem
if attackerArmy[j] >= defenderArmy[i] is true, d remains uninitialized causing the undefined behavior when you access its value in attackerArmy[d] = '0';.

Possible fix
Initialize d when you declare it.

ex:

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

Upvotes: 3

Related Questions