2
#include<stdio.h>
int main()
{
  char s[2]="a";
  s[1]='b';s[2]='c';s[3]='d';s[5]='e';
  printf("%s $%c$",s,s[4]);
  return 0;
 }

1.当我在 C (gcc-4.7.2) 中运行此程序时,由于缺少空字符 ('\0'),我预计会出现运行时错误。

2.如果程序仍然编译和执行成功,因为s[4]还没有被初始化,我预计那个地方会有一些垃圾值..但我也错了。

上述程序的输出是: abcde $$ 两个$(dollor) 之间没有字符,表示printf 跳过s[4]。这是相同的ideone链接:http: //ideone.com/UUQxb2

解释这种行为的原因(输出)?

4

3 回答 3

1

Accessing out of bound of an array is undefined behaviour. Just an example same code's output on my system is abcd(e▒x $($

string of length 8 is because of lack of NULL terminator and character ( between $ is garbage value of s[4].

于 2013-07-02T17:49:24.907 回答
1

您正在数组边界之外进行写入/读取,这只是未定义的行为,您无法对程序将执行的操作做出任何预测。

于 2013-07-02T17:45:33.507 回答
0
  1. It isn't necessary for a runtime error to occur. C does no bound checking.
  2. There are many characters defined in C. Like the sound beep \a if I remebember correct so it isn't necessary that something is actually printed on the screen. It might have been a sound that you never heard.
于 2013-07-02T17:49:31.443 回答