问题
Below is a C program to find the equilibrium point in the given array.
#include <stdio.h>
void equilibrium(int a[], int n)
{
int i;
int rsum[n], lsum[n];
lsum[0] = a[0];
rsum[0] = a[n-1];
for (i = 1 ; i < n ; i++) {
lsum[i] = lsum[i-1]+a[i];
}
printf("lsum array: ");
for (i = 0 ; i < n ; i++) {
printf("%d ",lsum[i]);
}
printf("\n\nrsum array: ");
for (i = n - 1 ; i >= 0 ; i--) {
rsum[i] = rsum[i + 1] + a[i];
}
for (i = 0 ; i < n ; i++) {
printf("%d ", rsum[i]);
}
printf("\n\n");
for (i = 1 ; i < n ; i++) {
if (lsum[i] == rsum[i])
printf("\n\n%d is equilibrium point", i);
}
}
int main()
{
int a[8] = {-1,3,-4,5,1,-6,2,1};
//printf("\n\n");
equilibrium(a,8);
return 0;
}
This code outputs as below which is correct:
lsum array: -1 2 -2 3 4 -2 0 1
rsum array: 1 2 -1 3 -2 -3 3 1
1 is equilibrium point
3 is equilibrium point
7 is equilibrium point
The problem occurs when I uncomment the
printf("\n\n");
in the main()
function.
Now the output changes as follows:
lsum array: -1 2 -2 3 4 -2 0 1
rsum array: -45602127 -45602126 -45602129 -45602125 -45602130 -45602131 -4560212
5 -45602127
If I include another int variable, say "int value = 1
" before declaring the "int a[8]
" array, the output changes to:
lsum array: -1 2 -2 3 4 -2 0 1
rsum array: 3 4 1 5 0 -1 5 3
Is this something to do with the memory?
Can someone please give a valid reason as to why this is happening?
回答1:
As the user @xing pointed out in this comment, your code is accesing the array beyond bounds. Because in the first iteration of the corresponding loop, the line
rsum[i + 1] + a[i]
is accessing rsum
at n
, and that is 1 position after the end of rsum
. This will cause what is known undefined behavior.
The effect of adding or removing printf()
simply changes the memory layout of the resulting program, the same thing that happens when you define another variable. In fact, any change to the memory layout of the program affects it's behavior, thus the word undefined.
回答2:
In this loop
for (i = n - 1 ; i >= 0 ; i--) {
rsum[i] = rsum[i+1]+a[i];
^^^^^^^^
there is an access memory beyond the array bounds. Thus the result depends on what is stored in the memory after the array.
来源:https://stackoverflow.com/questions/42238660/output-of-the-program-changes-with-printf-statement