简体   繁体   English

打印出串联字符串的长度

[英]Printing out the length of a concatenated string

#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)));
}

This prints out: 打印出:

hello 你好

HELLO 你好

helloHELLO 你好你好

12 12

Why 12? 为什么12?

But if I have this: 但如果我有这个:

#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)));
}

It prints out: 打印出来:

hello 你好

HELLO 你好

10 10

Could someone explain why the lengths are different here? 有人可以解释为什么这里的长度不同? I have a feeling that it's the '\\0' character though. 我觉得这是'\\ 0'字符。

strcat modifies the string pointed to by the first argument. strcat修改第一个参数指向的字符串。 That is, the string represented by the second argument is appended to the string of the first argument. 也就是说,第二个参数表示的字符串被附加到第一个参数的字符串。

Your char a[8] = "hello"; 你的char a[8] = "hello"; is 5 characters, plus a null, plus two unused bytes. 是5个字符,加上一个空字加上两个未使用的字节。 Then b follows it in memory. 然后b在内存中跟随它。

Before `strcat: 在`strcat之前:

a:  h e l l o \0 _ _
b:  H E L L O \0 _ _

After first strcat : 在第一次strcat

a:  h  e  l  l  o  H  E  L
b:  L  O  \0 L  O  \0 _  _

Now a has overwritten into b , and b points to the string "LO" in essence. 现在a已被覆盖为b ,而b本质上指向字符串“LO”。

Now the second strcat is concatenating "LO" to "helloHELLO". 现在第二个strcat将“LO”连接到“helloHELLO”。 After second strcat : 第二次strcat

a:  h  e  l  l  o  H  E  L
b:  L  O  L  O  \0 \0 _  _

Note the length of the string at a after the second strcat is 12 bytes: "helloHELLOLO". 注意字符串的长度在a第二后strcat长度为12字节:“helloHELLOLO”。

In your second test case, you eliminated the first strcat , so you saw what looks like normal output. 在你的第二个测试用例中,你删除了第一个strcat ,所以你看到了正常输出。 But, when you use strcat you must make sure your receiving buffer (the first argument) has enough room to hold the entire concatenated string plus null. 但是,当你使用strcat你必须确保你的接收缓冲区(第一个参数)有足够的空间来容纳整个连接字符串加上null。 When using C library functions it's advised to read the manual page. 使用C库函数时,建议阅读手册页。 See man strcat for details. 有关详细信息,请参阅man strcat

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM