0

这是代码。

int main(int argc, char *argv[])
{
    char name[5];

    printf("%s\n",name);

    system("PAUSE");
    return 1;
}

printf 函数输出 ©。为什么它使用那个字符?在不同的实例中使用其他字符。我试图更多地了解内存在 C 中的工作原理。

干杯:)

编辑 - 谢谢大家。你所有的答案对我都非常有用。

4

4 回答 4

2

tl; dr:该值未确定。

根据编译器,数组的值是不确定的(大多数情况下)或零(一些清理堆栈的特定编译器)。

大多数情况下,数组只是从堆栈中取出的一些内存空间,因此根据您使用它之前该内存区域的内容,您可以在其中拥有许多不同的值。

于 2013-04-26T12:02:13.343 回答
1

Since the array is declared in a function the initial value is undefined. If the array was declared global then it would have been initialized to all zeros. From the draft standard, section 6.7.9.10

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.

于 2013-04-26T12:00:46.637 回答
0

Per the standard, it's undefined, which means it could be anything. If you want to make sure it's one specific value, you have to set it yourself (e.g. using memset()).

This doesn't mean some compilers may set it to a specific value.

于 2013-04-26T12:00:41.980 回答
0

未初始化数组的使用是未定义的行为,因此 pritntf 调用可能导致任何结果,包括应用程序崩溃。在现实生活中,它会从堆栈中打印一些垃圾。

于 2013-04-26T12:01:11.060 回答