这里我想合并两个字符数组,并把它们放到第一个字符数组中,但是当我计算第二个字符数组时,它缺少了第一个字母,为什么?
#include <bits/stdc++.h>
using namespace std;
int main() {
char s1[4] = "one";
char s2[4] = "two" ;
strcat(s1, s2);
cout << s1 << endl; //onetwo
cout << s2; // wo
return 0;
}
2条答案
按热度按时间nbysray51#
调用函数
strcat
时,需要将一个指针作为第一个参数传递给内存缓冲区,该缓冲区足够大,可以存储连接的字符串。在本例中,连接的字符串长度为6个字符(
"onetwo"
),因此内存缓冲区的大小必须至少为7个字符(包括终止空字符)。但是,在您的情况下,内存缓冲区的大小只有4个字符,这是不够的。因此,您的程序正在调用undefined behavior,这意味着任何事情都可能发生。这包括你在问题中描述的行为。要解决此问题,必须使数组
s1
的长度至少为7个字符:此程序具有所需的输出:
vecaoik12#
在C++中,你应该使用
std::string
来处理字符串: