【发布时间】:2022-01-24 01:23:47
【问题描述】:
谁能解释我的代码有什么问题
#include <iostream>
#include <cstring>
#include <string.h>
using namespace std;
int main () {
char x[] = "abcdefghi123456"; // length 15
cout << "original string length: " << strlen(x) << endl;
cout << "string before modified: " << x << endl;
while ((strlen(x) % 4) != 0)
{
memcpy(x+strlen(x),"n",1);
}
cout << "string length after modified: " << strlen(x) << endl;
cout << "string after modified: " << x << endl;
return 0;
}
上面代码的结果是:
【问题讨论】:
-
一方面,没有代码,因为都是cmets
-
我还要指出,超出数组范围是未定义的行为;那时你不能指望任何事情。
-
是的。我可以解释。您使用的是 char[] 而不是
std::string。 char 数组的大小固定为 15,并且不会增长。如果你尝试用 memcpy 附加一些东西,你会越界。在 C++ 中不要对字符串使用 char 数组 -
这段代码应该做什么?不管是什么,它很可能不需要你以这种方式编写代码,即使用
memcpy,重复调用strlen,等等。
标签: c++