Output of a C string program

2020-02-07 05:09发布

#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.When I run this program in C (gcc-4.7.2) I expected Runtime Error because of the missing Null Character ('\0').

2.If still the program compiles and executes successfully ,since s[4] has not been initialised,I expected some garbage value at that place..but here also I was wrong.

The output of the above program is: abcde $$ There is no character between the two $(dollor) which indicates printf skips s[4]. here is a ideone link for the same: http://ideone.com/UUQxb2

Explain the reason for this behaviour (output) ?

3条回答
forever°为你锁心
2楼-- · 2020-02-07 05:52

You are writing/reading outside of the bounds of the array, this is simply undefined behavior you can not make any predictions about what the program will do.

查看更多
别忘想泡老子
3楼-- · 2020-02-07 06:00
  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.
查看更多
女痞
4楼-- · 2020-02-07 06:05

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].

查看更多
登录 后发表回答