开发者

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开发者_如何学Python 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? Isn't value[8] supposed be = value[6] = value[7] = 0? By the way, I compile the code via gcc under Mac OS X Lion.


value[8] was never initialized, therefore its contents are undefined and can be anything.

Same applies to value[1], value[4], value[6], and 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 (e.g. printing int) of an object which has an indeterminate value.

If you want the array to be initialized to zero you need to provide an initializer. E.g.

int value[10] = {0};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜