简体   繁体   English

不明白这个C程序的输出

[英]Don't understand the output of this C program

Here's the code: 这是代码:

#include <stdio.h>

int main (void)
{
    int value[10];
    int index;

    value[0] = 197;
    value[2] = -100;
    value[5] = 350;
    value[3] = value[0] + value[5];
    value[9] = value[5] / 10;
    --value[2];

    for(index = 0; index < 10; ++index)
        printf("value[%i] = %i\n", index, value[index]);
    return 0;
}

Here's the output when compile: 这是编译时的输出:

value[0] = 197
value[1] = 0
value[2] = -101
value[3] = 547
value[4] = 0
value[5] = 350
value[6] = 0
value[7] = 0
value[8] = 1784505816
value[9] = 35

I don't understand why value[8] returns 1784505816? 我不明白为什么价值[8]会返回1784505816? Isn't value[8] supposed be = value[6] = value[7] = 0? 不是值[8]假设是=值[6] =值[7] = 0? By the way, I compile the code via gcc under Mac OS X Lion. 顺便说一下,我在Mac OS X Lion下通过gcc编译代码。

value[8] was never initialized, therefore its contents are undefined and can be anything. value[8]从未初始化,因此其内容未定义,可以是任何内容。

Same applies to value[1] , value[4] , value[6] , and value[7] . 同样适用于value[1]value[4]value[6]value[7] But they just happened to be zero. 但他们恰好是零。

Objects with automatic storage duration declared without an initializer have indeterminate values until they are assigned to. 在没有初始化程序的情况下声明自动存储持续时间的对象在分配给它们之前具有不确定的值。 Technically, it causes undefined behavior to use the value (eg printing int) of an object which has an indeterminate value. 从技术上讲,它会导致未定义的行为使用具有不确定值的对象的值(例如,打印int)。

If you want the array to be initialized to zero you need to provide an initializer. 如果要将阵列初始化为零,则需要提供初始化程序。 Eg 例如

int value[10] = {0};

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

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