c ++我想连接字符,但出现分段错误

c++ i want to concat char but i get an segmentation fault

我有一个简短的问题,我如何在 C++ 中连接这些字符。我总是遇到分段错误

struct dirent *ent
const char *filePath = strcat("/test/",ent->d_name) ;

连接字符串的 C 方法是这样的:

char buf[128];
strcpy(buf, "first string");
strcat(buf, "second string");

首先我们分配 space 来保存连接的字符串。然后我们将第一个字符串复制到缓冲区中。然后我们将第二个字符串连接到第一个字符串上。

但是由于您使用的是 C++,因此您真的应该使用 std::string 而不是 str* 函数。

std::string j = "hello";
j += " there";

你读过 documentation 了吗?

Appends a copy of the character string pointed to by src to the end of the character string pointed to by dest. The character src[0] replaces the null terminator at the end of dest. The resulting byte string is null-terminated.

The behavior is undefined if the destination array is not large enough for the contents of both src and dest and the terminating null character.

"/test/" 首先是不可修改的字符数组,更不用说“足够大以容纳 src 和 dest 的内容以及终止空字符”了。

如果您启用了足够高的编译器警告级别,编译器还会告诉您一些关于在预期 char* 的地方传递 const char[] 的信息。

struct dirent *ent
const char *filePath = strcat("/test/",ent->d_name) ;

我发现 std::stringstream 更加灵活:

std::stringstream filePathSS;

// streams know how to handle c-style nullterminated
filePathSS << "/test/" << ent->d_name

// and numbers
           << "_" << i++   // to create a unique file each use

// and std::string
           << "." << suffix; // append a const std::string

访问 const char* 很简单,通过:

const char* filePath = filePathSS.str().c_str();