为什么控制台输出不显示"Hello"?(请参阅所附 test.c 中的第 43 行)


  • 下面复制的源代码文件(test.c(有我的c代码和控制台输出被注释掉
  • 我正试图弄清楚为什么";你好"未打印到控制台输出
  • 我相信这可能与scanf([^n])有关从前一行读取CCD_ 2(参见第14和15行(
#include <stdio.h>
#include <string.h>

#define MAX_LEN 16

int main(){
char ch;
char s[MAX_LEN]; 
char sen[MAX_LEN];
scanf("%c", &ch);
scanf("%s", s);

scanf("n");
scanf(" %[^n]", sen);
scanf("%*c");
printf("%cn", ch);
printf("%sn", s);
printf("%sn", sen);
printf("sen[15] = %cn", sen[15]);
printf("string length = %lun", strlen(sen)); 
return 0;
}

输出

user@MacBook-18 c_the_hard_way % ./test
C
Hello
My name is Mikey
C

My name is Mikey
sen[15] = y
string length = 16

问题就在这里:

#define MAX_LEN 16

给定的字符串长度:

My name is Micky

长度为16,但没有null终止符。将MAX_LEN更改为17

如果我们做一些小的更改,我们可以看到为什么Hello没有打印:

#include <stdio.h>
#include <string.h>

#define MAX_LEN 16

int main(){
char ch;
char s[MAX_LEN]; 
char sen[MAX_LEN];
scanf("%c", &ch);
scanf("%s", s);

scanf("n");
scanf(" %[^n]", sen);
scanf("%*c");
printf("%cn", ch);
printf("%sn", s);
printf("%sn", sen);
// The null terminator from the second string is getting written
// to the start of the storage for "Hello"
printf("s[0] = %dn", (int) s[0]);
// Let's try to print "Hello" now that we know what is happening
printf("%sn", &s[1]);
printf("sen[15] = %cn", sen[15]);
printf("string length = %lun", strlen(sen)); 
return 0;
}

输出

C
Hello
My name is Mikey
C
My name is Mikey
s[0] = 0
ello
sen[15] = y
string length = 16

在这里,我们看到Hello的开始被My name is Mickey的空终止符覆盖。

在线运行此代码

注意

语言律师会突然说,你正在经历的是";未定义行为";并且不能保证上述输出是相同的。然而,在这种情况下,编译器实现非常相似,因此我们得到了相同的输出。

最新更新