对于某些函数我想在函数中创建一个字符串的副本,然后操纵它 - 由于一些奇怪的原因,我不能strcpy工作(给我一个分段错误) - 我也尝试将arg作为字符串传递,这也不起作用(g ++抛出一个错误,说它期望一个char*)
#include <iostream>
#include <cstring>
using namespace std;
void copy_string(char* stri);
int main ()
{
copy_string("sample string");
return 0;
}
void copy_string(char* stri) {
char* stri_copy;
strcpy(stri_copy, stri);
cout << "String: " << stri_copy;
}
Run Code Online (Sandbox Code Playgroud)
我不确定我明白为什么会这样.
所以我的两个问题是:
谢谢!
char* stri_copy;
stri_copy = (char*)malloc(strlen(stri) * sizeof(char) + 1);
strcpy(stri_copy, stri);
Run Code Online (Sandbox Code Playgroud)
您没有为stri_copy分配空间.