Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
打印出连接字符串的长度 #包括 #包括 void main() { 字符a[8]=“你好”; 字符b[8]=“你好”; int x=strcmp(a,b); printf(“%s\n%s\n”,a,b); printf(“%s\n”,strcat(a,b)); printf(“%d”,strlen(strcat(a,b)); }_C_String - Fatal编程技术网

打印出连接字符串的长度 #包括 #包括 void main() { 字符a[8]=“你好”; 字符b[8]=“你好”; int x=strcmp(a,b); printf(“%s\n%s\n”,a,b); printf(“%s\n”,strcat(a,b)); printf(“%d”,strlen(strcat(a,b)); }

打印出连接字符串的长度 #包括 #包括 void main() { 字符a[8]=“你好”; 字符b[8]=“你好”; int x=strcmp(a,b); printf(“%s\n%s\n”,a,b); printf(“%s\n”,strcat(a,b)); printf(“%d”,strlen(strcat(a,b)); },c,string,C,String,这将打印出: 你好 你好 你好 十二, 为什么是12岁 但如果我有这个: #include <stdio.h> #include <string.h> void main() { char a[8] = "hello"; char b[8] = "HELLO"; int x = strcmp(a,b); printf("%s \n%s \n", a, b); printf("%s\n", strcat(a,b)); printf("%d

这将打印出:

你好

你好

你好

十二,

为什么是12岁

但如果我有这个:

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

void main()
{
  char a[8] = "hello";
  char b[8] = "HELLO";

  int x = strcmp(a,b);

   printf("%s \n%s \n", a, b); 

  printf("%s\n", strcat(a,b));
  printf("%d", strlen(strcat(a,b)));
}
#包括
#包括
void main()
{
字符a[8]=“你好”;
字符b[8]=“你好”;
int x=strcmp(a,b);
printf(“%s\n%s\n”,a,b);
//printf(“%s\n”,strcat(a,b));
printf(“%d”,strlen(strcat(a,b));
}
它打印出:

你好

你好

十,


有人能解释一下为什么这里的长度不同吗?我感觉它是'\0'字符。

strcat
修改第一个参数指向的字符串。也就是说,由第二个参数表示的字符串被附加到第一个参数的字符串

你的
chara[8]=“你好”是5个字符,加上一个空字符,再加上两个未使用的字节。然后
b
在内存中跟随它

在“strcat”之前:

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

 void main()
 {
  char a[8] = "hello";
  char b[8] = "HELLO";

  int x = strcmp(a,b);

  printf("%s \n%s \n", a, b); 

  //printf("%s\n", strcat(a,b));
  printf("%d", strlen(strcat(a,b)));
}
在第一个strcat之后

a:  h e l l o \0 _ _
b:  H E L L O \0 _ _
a:  h  e  l  l  o  H  E  L
b:  L  O  \0 L  O  \0 _  _
现在
a
已经覆盖到
b
,而
b
本质上指向字符串“LO”

现在,第二个strcat将“LO”连接到“helloHELLO”。在第二次strcat之后:

a:  h e l l o \0 _ _
b:  H E L L O \0 _ _
a:  h  e  l  l  o  H  E  L
b:  L  O  \0 L  O  \0 _  _
请注意,第二个strcat之后
a
处的字符串长度为12字节:“hellohello”


在第二个测试用例中,您消除了第一个strcat,因此您看到了正常的输出。但是,当使用strcat时,必须确保接收缓冲区(第一个参数)有足够的空间容纳整个连接字符串加上null。使用C库函数时,建议阅读手册页。有关详细信息,请参见
manstrcat

我只想补充一点,调用
strcat
两次,将
a
作为第一个参数,并期望两次的结果相同,这也是一个错误(尽管一位精明的读者已经从你指出的
strcat
修改了它的第一个参数中得出了这个结论)。