程序的输出通过printf()语句更改 [英] Output of the program changes with printf() statement
问题描述
下面是一个C程序,用于在给定数组中找到平衡点.
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");
在 main()
函数中.
现在输出更改如下:
lsum array: -1 2 -2 3 4 -2 0 1
rsum array: -45602127 -45602126 -45602129 -45602125 -45602130 -45602131 -4560212
5 -45602127
如果我包含另一个int变量,则在声明" int a [8]
"数组之前说" int value = 1
",输出将更改为:>
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?
推荐答案
作为用户@ xing 在此注释,您的代码正在访问数组..因为在相应循环的第一次迭代中,该行
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]
正在访问 n
处的 rsum
,该地址位于 rsum
末尾的1个位置.这将导致已知的未定义行为.
is accessing rsum
at n
, and that is 1 position after the end of rsum
. This will cause what is known undefined behavior.
添加或删除 printf()
的效果只是更改了结果程序的内存布局,这与定义另一个变量时发生的情况相同.实际上,对程序内存布局的任何更改都会影响其行为,因此,单词 undefined .
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.
这篇关于程序的输出通过printf()语句更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!