Output of a C string program

时间秒杀一切 提交于 2019-11-27 08:18:35

问题


#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) ?


回答1:


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.




回答2:


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




回答3:


  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.


来源:https://stackoverflow.com/questions/17432222/output-of-a-c-string-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!