作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在编写一个基本的C程序来显示两个字符串,一个取自用户,即“a”,另一个在代码“b”中定义,但是当我运行下面的代码时,字符串“a”被附加到“b” 。为什么? “a”末尾的符号是什么
更新的代码:
#include <stdio.h>
#include <string.h>
int main()
{
char a[ 5 ];
int i=0;
while(i<5)
{
a[i]=getchar();
i++;
}
char b[]={'r','f','s','/0'};
printf("output:-");
printf("\n %s",a);
printf("\n %s",b);
return 0;
控制台
qwert
output:-qwert$
rfs$qwert$
上面有一个特殊的符号代替$,它是什么?
最佳答案
将所有评论放入答案中。原始代码中的问题主要源于未使用 NUL 终止字符数组来生成有效的 C 字符串。
a
不以 NUL 结尾。可以通过将 a
数组加 1 并显式将 NUL 写入最后一个字节来修复。b
未以 NUL 结尾。可以通过使用文字字符串或以 '\0'
作为最后一个字节的字符数组初始化 b
来修复。下面的示例使用前者。这是已更正错误的完整代码。请注意,读取输入的代码很脆弱,因为它只接受 5 个字符的字符串。
#include <stdio.h>
#include <string.h>
int main(void)
{
char a[6];
int i=0;
while (i<5) {
a[i]=getchar();
i++;
}
a[i] = '\0';
char b[]="rfs";
printf("output:-\n");
printf(" %s\n",a);
printf(" %s\n",b);
return 0;
}
关于c - 为什么在此代码中字符串 a 附加到字符串 b,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36382308/
我是一名优秀的程序员,十分优秀!