1
int avg(int *p);

int main()
{
    int i, average, mark[5];
    int arr[5];

    for(i = 0; i < 5; i++);
    {
        arr[i] = scanf_s("%d\n", &mark[i]);
    }
    average = avg(arr);
}

int avg(int *p)
{
    int j, total = 0, avg;

    for(j = 0; j < 5; j++)
    {
        total += p[j];
    }
    avg = total / 5;
    return avg;
}

This program did not cause any errors.But while running I am getting "Run-Time Check Failure #2 -stack around the variable "mark" was corrupted. Can some one please explain the reason behind this?

1
  • 1
    Another reason for Egyptian brackets/K&R style: you have a (probably unintended) semicolon after your for in main. Commented Nov 30, 2013 at 11:54

4 Answers 4

1

why you are using semicolon at the end of for loop..?

for(i = 0; i < 5; i++);

remove that semicolon and check

Sign up to request clarification or add additional context in comments.

Comments

1
for(i = 0; i < 5; i++);

I don't think you want that semicolon there!

Comments

1

Firstly about the fix:

for(i = 0; i < 5; i++)
    {
        arr[i] = scanf_s("%d\n", &mark[i]);
    }

This is just okey. Now reason of Run-Time Check Failure #2 -stack around the variable "mark" was corrupted : when you run:

for(i = 0; i < 5; i++);

After this line i = 5 Now you are doing arr[i] = scanf_s("%d\n", &mark[i]); Now arr[5] is not a leagal area for you. This is the reason of your error.

Comments

0

I'd like to add a little explanation to the other answers.

The for loop does essentially nothing, except incrementing i until it is n longer < 5.

So if you leave the for loop, you have i = 5, and this is used for accessing arr and mark. Neither arr[5] nor mark[5] is valid, so your error happens.

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.