【问题标题】:How to copy or concatenate two char*如何复制或连接两个 char*
【发布时间】:2012-05-23 11:19:30
【问题描述】:

如何将 char* 连接或复制在一起?

char* totalLine;

const char* line1 = "hello";
const char* line2 = "world";

strcpy(totalLine,line1);
strcat(totalLine,line2);

此代码产生错误!

segmentation fault

我猜我需要为 totalLine 分配内存?

还有一个问题,下面是复制内存还是复制数据?

char* totalLine;

const char* line1 = "hello";

 totalLine = line1;

提前致谢! :)

【问题讨论】:

  • 只需将char* totalLine 更改为char totalLine[12](尽管请记住您的代码是C 而不是C++)
  • 你总是可以把它们放在短字节的低位和高位字节中;)
  • 你为什么不使用std::string?它神奇地解决了所有问题。

标签: c++ strcpy strcat


【解决方案1】:

我猜我需要为 totalLine 分配内存?

是的,你猜对了。 totalLine 是一个未初始化的指针,所以那些 strcpy 调用试图写入内存中的某个随机位置。

幸运的是,由于您已标记此 C++,因此您无需为所有这些烦恼。只需这样做:

#include <string>

std::string line1 = "hello";
std::string line2 = "world";

std::string totalLine = line1 + line2;

不需要内存管理。

下面是复制内存还是复制数据?

我认为您的意思是“是复制了底层字符串,还是只是复制了指针?”。如果是这样,那么只是指针。

【讨论】:

  • 您好,感谢您的回复!我从文件中获取数据,然后将其 strtok,因此我将以 char* 格式保存它。我如何将其转换为字符串?不然怎么解决?
  • std::string 有一个来自 char * 的构造函数,使用它即可。
  • 参考链接,不知道文字大小怎么办?那我怎么把它转换成字符串呢?
  • @dupdupdup:你不需要知道大小。 const char *foo = "whatever"; std::string bar = foo; 应该可以正常工作。
  • @dupdupdup:您可能不应该使用 strtok()。你应该问另一个问题,关于如何完成你在 C++ 中所做的任务(因为你显然是在写 C 而不是 C++)。
【解决方案2】:

是的,您需要为totalLine 分配内存。这是一种方法;这恰好是我推荐的方法,但还有许多其他方法也一样好。

const char *line1 = "hello";
const char *line2 = "world";

size_t len1 = strlen(line1);
size_t len2 = strlen(line2);

char *totalLine = malloc(len1 + len2 + 1);
if (!totalLine) abort();

memcpy(totalLine,        line1, len1);
memcpy(totalLine + len1, line2, len2);
totalLine[len1 + len2] = '\0';

[编辑:我写这个答案是假设这是一个 C 问题。在 C++ 中,正如 Oli 建议的那样,只需使用 std::string]

【讨论】:

  • 为什么不strcpystrcat
  • @MooingDuck 我认为先调用strlen,然后使用malloc 中使用的相同长度变量调用memcpy,让我的代码的未来读者更清楚没有缓冲区溢出的可能性。此外,在这种情况下也没关系,但如果有 N 个字符串要连接,使用 strcat 将使运算 O(N²)。
【解决方案3】:

totalLine 有一个垃圾值

const char* Line1{ "Hallo" };  
const char* Line2{ "World" };   
char* TotalLine{ new char[strlen(Line1) + strlen(Line2) + 1] };

TotalLine = strcpy(TotalLine, Line1);
TotalLine = strcat(TotalLine, Line2);

注意=>如果您使用 Visual Studio,则需要 #define _CRT_SECURE_NO_WARNINGS

【讨论】:

    【解决方案4】:

    将“aaa”和“bbb”集中到“aaabbb”:

    #include <iostream>
    #include <cstring>
    using namespace std;
    
    int main() {
        const char* Line1 ="aaa";
        const char* Line2 ="bbb";
        char* TotalLine{ new char[strlen(Line1) + strlen(Line2) + 1] };
        TotalLine = strcpy(TotalLine, Line1);
        TotalLine = strcat(TotalLine, Line2);   
        cout << TotalLine <<endl;
    }
    

    【讨论】:

      猜你喜欢
      • 2013-06-08
      • 1970-01-01
      • 1970-01-01
      • 2018-11-06
      • 2020-02-29
      • 2021-07-11
      • 2018-11-06
      • 2023-03-22
      • 1970-01-01
      相关资源
      最近更新 更多