#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) ?
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.
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]
.
- It isn't necessary for a runtime error to occur. C does no bound checking.
- 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