gpt4 book ai didi

c++ - C++ 中的 Cstring - 使用标准 C 函数导致段错误

转载 作者:太空宇宙 更新时间:2023-11-04 14:36:09 25 4
gpt4 key购买 nike

<分区>

对于某些函数,我想在函数中创建一个字符串的拷贝,然后对其进行操作 - 出于某种奇怪的原因,我无法让 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;

}

我不确定我明白为什么会这样。

所以我的两个问题是:

  1. 为什么会出现这种情况 - 是否有简单的解决方法?
  2. 创建传递给函数的字符串的本地拷贝的最简单/最有效的方法是什么?

谢谢!

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com