0

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");
}
1
  • 1
    The most probable cause of your problem is accessing a non-existing element of the array due to discrepancy between the declared size of an array and the range of iteration, as Cameron Tinker describes in the answer. Accessing the tie_count variable after the loop has nothing to do with seg.fault. Commented Oct 4, 2021 at 18:30

1 Answer 1

2

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++)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.