gpt4 book ai didi

c - 为什么在此代码中字符串 a 附加到字符串 b

转载 作者:行者123 更新时间:2023-11-30 15:10:06 25 4
gpt4 key购买 nike

我正在编写一个基本的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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com