C 字符串程序的输出 [英] Output of a C string program
问题描述
#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'),我预计会出现运行时错误.
1.When I run this program in C (gcc-4.7.2) I expected Runtime Error because of the missing Null Character ('\0').
2.如果程序仍然编译并成功执行,由于 s[4] 尚未初始化,我希望在那个地方有一些垃圾值..但在这里我也错了.
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.
上述程序的输出为:abcde $$两个 $(dollor) 之间没有表示 printf 跳过 s[4] 的字符.这是相同的ideone链接:http://ideone.com/UUQxb2
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) ?
推荐答案
越界访问数组是未定义的行为.只是一个示例,我的系统上相同代码的输出是 abcd(e▒x $($
Accessing out of bound of an array is undefined behaviour. Just an example same code's output on my system is abcd(e▒x $($
长度为8的字符串是因为缺少NULL终止符和字符(
是$
之间的s[4]
的垃圾值.
string of length 8 is because of lack of NULL terminator and character (
between $
is garbage value of s[4]
.
这篇关于C 字符串程序的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!