好奇的数组覆盖

Curious array overwrite

我写了下面的c程序:

int main() 
 {
     char a[1];
     char b[6]="hello[=10=]";
     int c,  i;

     for(i = 0; (c = getchar()) != EOF; i++) 
         a[i] = c;
     for(i = 0; i  < 5; i++) 
         printf("%c", b[i]);

 }

为什么当我输入"bye"时程序打印"helby"? 我认为 'b' 应该保存在 a[0] 中, 'y' 保存在 b[0] 中, 'e' 保存在 b[1] 中。 谢谢指教!

您假设 a 在内存中紧随其后的是 b。不一定如此。

Reading/writing 数组末尾之后是 undefined behavior,因此编译器可以自由地按照他们选择的任何顺序排列局部变量。

在我的特定机器上,如果 ba 之前声明,那么 a 会出现在内存中的 b 之前,我会得到您期望的输出。但是,正如您从其他答案和评论中看到的那样,由于未定义的行为,行为不可靠。

Why when I give "bye" in input the program print "helby"?

在程序中,您试图在此循环中超出数组 a[] 的范围进行访问:

 for(i = 0; (c = getchar()) != EOF; i++) 
     a[i] = c; //only defined behaviour for `i = 0`

例如,当您将 bye 作为输入时,

a[0] -> overwritten with b
a[1] -> undefined behaviour as you are accessing out of bounds
a[2] -> same as a[1]

在这里你可以看到 b[] 数组没有任何变化。

它会导致未定义的行为。所以你的输出可以是任何东西(从无到有)