在c++中构建/合并字符数组指针

Building / Merging character array pointers in C++

本文关键字:字符 数组 指针 合并 c++ 构建      更新时间:2023-10-16

我对c++很陌生(来自c#),它让我感到困惑:S

我有一个关于数组和指针的基本问题。

如果我有下面的代码:

char * test1 = "com";
char * test2 = "ment";

我已经在一些文件中发现了类似的代码。我不太明白一个字符怎么能容纳一个字符串。但是好…

然而,我如何将这些数组连接起来才能得到"comment" ?

我很确定这个char * result = test1 + test2;只会增加指针,然后指向内存中的某些东西,我不打算使用。

所以有可能得到一个数组像char array[] = {'c', 'o', 'm', 'm', 'e', 'n', 't'};从这回来吗?

或者我至少可以得到一个指针指向内存中的commentNUL之类的东西吗?

正如你所指出的,指针算术不能解决这个问题。

如果你想要一个c字符串作为结果,需要为整个新字符串分配空间,然后复制字符,通常使用strcat/strncat,但它们是c风格的字符串操作。

// Your C-strings
const char *test1 = "com";
const char *test2 = "ment";
// Dynamic allocation of memory for result string
char *result = new char[strlen(test1) + strlen(test2) + 1];
// Start with the empty string
*result = '';
// Concatenate both input strings (use strncat if you don't know
// for sure that they will fit into the result array!)
strcat(result, test1);
strcat(result, test2);
// (use result pointer)
// Free the memory after last usage
delete[] result;

在c++中,通常会尽量避免使用它们,而使用std::string。即使您想要一个C-string作为结果,您也可以使用一个临时的std::string来分配和管理所需的内存以及执行连接:

// Your C-strings
const char *test1 = "com";
const char *test2 = "ment";
// Wrap in temporary C++ strings and concatenate:
std::string result = std::string(test1) + std::string(test2);
// Get the pointer (only valid as long as result is in scope!)
const char *ptr = result.c_str();

此外,请注意不要将字符串字面值赋值给非const char *指针,而应使用const char*指针。尽量避免处理原始c字串;当然,当你使用C库时,你必须经常使用它们。

还要注意,上面提到的方法是在运行时执行的;即使编译器可以知道您想要的是什么,您也无法获得连接两个字符串字面值的编译时解决方案。我不知道你的上下文,但也许你只想有一个多行字符串文字,然后简单地放下+,写"com" "ment"

c风格的解决方案可以在以下链接中找到:http://www.cplusplus.com/forum/beginner/5681/:

int len = strlen(test1)+strlen(test2);
char* result = new char[len +1]; // +1 for null terminated string
snprintf(result,len +1, "%s%s",test1,test2);
result[len] = NULL; 
// use result
delete(result);

您可以使用std::string:

#include <iostream>
int main() {
    // Note: the character literals are const (non const is deprecated)!
    const char * test1 = "com";
    const char * test2 = "ment";
    // This gives a compiler error (there is no way to add pointers)
    // const char * concat = test1 + test2;
    // A std::string has an overload for the operator +:
    std::string comment = std::string(test1) + test2;
    // The dynamically allocated string.
    // Note: as soon as the comment string gets altered or destroyed the 
    // pointer s to the internal string data (may) become invalid.
    const char* s = comment.c_str();
    std::cout << s << 'n';
}