Reputation: 11
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?
Upvotes: 1
Views: 83
Reputation: 91017
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.
Upvotes: 0
Reputation: 3379
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.
Upvotes: 1
Reputation: 4571
for(i = 0; i < 5; i++);
I don't think you want that semicolon there!
Upvotes: 1
Reputation: 3605
why you are using semicolon at the end of for loop..?
for(i = 0; i < 5; i++);
remove that semicolon and check
Upvotes: 1