Home > Enterprise >  How to work through segmentation fault for "[For loop] variables"?
How to work through segmentation fault for "[For loop] variables"?

Time:10-05

I think I understand why I get the segmentation fault error (tie_count will be 0 and I tried to use it outside the loop). But how do I get to condition the variables that changed inside the loop after the loop has been finished? or am i brain ded?

int x = 0, tie_count = 0, tie[8];

for (int i = 0; i < 10; i  )
{
    if ( //anything here )
    {
        //anything here
    }
    else
    {
        tie[x] = 1;
        x  ;

        tie_count  ;

    }
}

if (tie_count > 1)
{
    printf("%there is tie.\n");
}
else
{
    printf("no tie.\n");
}

CodePudding user response:

Arrays are 0 based and you have a non-inclusive upper boundary of 10 on your loop condition. You have your tie array initialized as an integer array of length 8. This means that you're looping 10 times and the code may attempt to assign to an index that is larger than the array.

Without knowing the logic of your original if block, you need to either increase tie to have 10 elements or decrease your maximum loop value.

Try the following changes to suit your needs:

Either this:

int x = 0, tie_count = 0, tie[10];

for (int i = 0; i < 10; i  )

Or this:

int x = 0, tie_count = 0, tie[8];

for (int i = 0; i < 8; i  )
  • Related