简体   繁体   English

程序的输出通过printf()语句更改

[英]Output of the program changes with printf() statement

Below is a C program to find the equilibrium point in the given array. 下面是一个C程序,用于查找给定数组中的平衡点。

#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. main()函数中。

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: 如果我包含另一个int变量,则在声明“ int a[8] ”数组之前说“ int value = 1 ”,输出将更改为:

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? 有人可以提供一个合理的原因来说明为什么会这样吗?

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. 因此,结果取决于数组之后存储在存储器中的内容。

As the user @ xing pointed out in this comment , your code is accesing the array beyond bounds. 正如@ xing用户在此注释中指出的那样,您的代码正在访问数组。 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 . 正在访问n rsum ,即rsum结束后的1个位置。 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. 添加或删除printf()只是更改了结果程序的内存布局,与定义另一个变量时发生的情况相同。 In fact, any change to the memory layout of the program affects it's behavior, thus the word undefined . 实际上,对程序内存布局的任何更改都会影响其行为,因此会出现undefined一词。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM