【发布时间】:2017-06-07 09:51:52
【问题描述】:
我有两个字符数组。当我尝试使用 strcat 函数连接两个字符串时。 然后我的字符串“a”长度从 9 减少到 6。 我也丢失了我的字符串“a”。字符串 b 也发生了变化。请参阅输出。为什么会这样???
这就是我所做的
#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()就是这么做的?您是否考虑过查阅文档?而不是猜测? -
@EJP 那么为什么 char 数组 "a" 改变了? char arrya "b" 只能更改。
-
因为您的
b泛滥并从事未定义的行为。 -
它的 C++。使用 std::string!。