为什么在使用 strcat 函数后原始字符串发生了变化?

Why after using strcat function original string changed?

我有两个字符数组。当我尝试使用 strcat 函数连接两个字符串时。 然后我的字符串 "a" 长度从 9 减少到 6。 我也丢失了我的字符串 "a" .string b changed too.See 在输出中。为什么会这样???

这是我所做的

#include <bits/stdc++.h>

using namespace std;
int main() {
    char a[]="roomies!!";
    char b[]="hey kammo DJ ";
    char *c;
    c=new char[50];
    cout<<"before:-\n";
    cout<<"len of a is "<<strlen(a)<<'\n';
    cout<<"len of b is "<<strlen(b)<<'\n';
    cout<<"len of c is "<<strlen(c)<<'\n';
    cout<<"string a is = "<<a<<'\n';
    cout<<"string b is = "<<b<<'\n';
    cout<<"string c is = "<<c<<'\n';
    c=strcat(b,a);
    cout<<"\nafter:-\n";
    cout<<"len of a is "<<strlen(a)<<'\n';
    cout<<"len of b is "<<strlen(b)<<'\n';
    cout<<"len of c is "<<strlen(c)<<'\n';
    cout<<"string a is = "<<a<<'\n';
    cout<<"string b is = "<<b<<'\n';
    cout<<"string c is = "<<c<<'\n';
return 0;
}

输出:-

before:-
len of a is 9
len of b is 13
len of c is 3
string a is = roomies!!
string b is = hey kammo DJ
string c is = =

after:-
len of a is 6
len of b is 22
len of c is 22
string a is = mies!!
string b is = hey kammo DJ roomies!!
string c is = hey kammo DJ roomies!!

strcat on C++ reference

Appends a copy of the source string to the destination string. The terminating null character in destination is overwritten by the first character of source, and a null-character is included at the end of the new string formed by the concatenation of both in destination.

您可以使用 std::string 以获得所需的结果。

strcat() 将源字符串附加到目标字符串,returns 将目标字符串附加到目标字符串。

char * strcat ( char * destination, const char * source ); 

所以你的说法

c = strcat(b,a) 

因此数组 b 和 c 将具有相同的值。 strcat()

编辑: "a" 已更改,因为 "b" 数组溢出。由于它的 c++,你可以只使用 std::string 而不是字符数组。

std::string a = "hi" ; 
std::string b = "this is concat" ;
std::string c = a + b ;

根据strcat spec

"The behavior is undefined if the destination array is not large enough for the contents of both src and dest and the terminating null character."

你的目标数组是 "b",它显然不够大,无法存储 "a" 和 "b" 的内容,所以你得到了一个未定义的行为,导致修改 "a" 字符串.

函数 strcat 具有签名 char *strcat( char *dest, const char *src ) 并在 dest 指向的字符串末尾附加字符串 src 的内容,即它 改变dest指向的内存内容。这要求 dest 指向的内存足够大以容纳字符串 srcdest

因此,您的调用 strcat(b,a) 实际上会产生未定义的行为,因为 b 表示的内存块能够容纳 14 个字节(即 "hey kammo DJ "+ 1 的长度),但不适用于任何其他字符串。

所以你宁愿写这样的东西:

strcpy (c,b);
strcat (c,a);

或:

snprintf(c, 50, "%s%s", b, a);