C++ 使用Strcpy_复制动态分配的字符数组
我只是试图将“temp”中的内容复制到“p”中,但程序在strcopy_s行中崩溃。我错过了一些重要的规则吗C++ 使用Strcpy_复制动态分配的字符数组,c++,C++,我只是试图将“temp”中的内容复制到“p”中,但程序在strcopy_s行中崩溃。我错过了一些重要的规则吗 #include <iostream> #include <string> #include <cstring> using namespace std; int main() { char temp[100] = "Coolbeans"; int len = strlen(temp); char* p = new char
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main() {
char temp[100] = "Coolbeans";
int len = strlen(temp);
char* p = new char[len+1];
strcpy_s(p, len, temp);
for (int i = 0; i < len; i++)
cout << p[i] << endl;
for (int i = 0; i < len; i++)
cout << temp[i] << endl;
}
#包括
#包括
#包括
使用名称空间std;
int main(){
字符温度[100]=“Coolbeans”;
int len=strlen(温度);
char*p=新字符[len+1];
strcpy_s(p、len、temp);
对于(int i=0;i coutPraetorian击中了它的头部。“你缺少的重要规则是使用std::string
”。像strcpy_s
这样的旧C函数是出了名的难以置信的不可靠,这就是不再这样做的全部意义。所以不要这样做。使用std::string
上面的代码片段会导致“调试断言失败”运行时错误
strcpy_s(p, len, temp); //Expression:(L"Buffer is too small" &&0)
所以答案是strcpy_s(p,len+1,temp);在您的情况下可以正常工作。您缺少的重要规则是使用std::string
。传递到strcpy的长度应该是len+1
,而不是len
。另外,您更喜欢strcpy
和memcpy
到strcpy
。谢谢。添加len+1解决了这个问题。(:只是如果他尝试编写更多的字符串处理函数,他会一次又一次地把它们搞乱,即使他成功了,它们也会无法读取和维护。这不是一个有用的答案。