代码之家  ›  专栏  ›  技术社区  ›  kuybt6

如何将char数组(或其一部分)存储到constchar*中?

  •  1
  • kuybt6  · 技术社区  · 3 年前

    我是C++的新手,很难将constchar*与char-aray连接起来。

    首先,我想问一个问题:const-char*和std::string一样吗?

    直接谈到我的问题,这就是我正在尝试的:

    我有一个10大小的char数组,其中包含从a到j的字母:

    char my_array[10] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', j};
    

    我想使用constchar*来存储这个数组(或它的一部分)。但我无法进行串联,我以为会有这样的想法:

        const char* group_of_letters = "\0";
        
        for(int i = 0; i <= 9; i++){
            group_of_letters += my_array[i];
        }
    

    我想使用for循环,因为我在实际项目中需要它来将该数组的定义间隔存储到const char中* 但我尝试过的方法都没有奏效。

    如果有帮助的话,我的完整代码如下所示:

    #include <iostream>
    
    int main(){
        
        char my_array[10] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
        const char* group_of_letters = "\0";
        
        for(int i = 0; i <= 9; i++){
            group_of_letters += my_array[i];
        }
        
        std::cout << group_of_letters;
        
        return 0;
    }
    

    ->使用开发程序C++5.11-06/08/2023

    1 回复  |  直到 3 年前
        1
  •  3
  •   wohlstad    3 年前

    首先,我想问一个问题:const-char*和std::string一样吗?

    不,它们不一样, const char* 是指向C样式字符串中的字符序列的指针,而 std::string 是一个C++类,它通过自动内存管理来管理和操纵字符串。

    不能将 char* 使用 + 操作人员

    在你的情况下,最好使用 std::字符串 如下所示:

    #include <iostream>
    #include <string>
    
    int main(){
        
        char my_array[10] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
        std::string group_of_letters;
        
        for(int i = 0; i <= 9; i++){
            group_of_letters += my_array[i];
        }
        
        std::cout << group_of_letters << std::endl;
        
        return 0;
    }
    
        2
  •  0
  •   Iman Abdollahzadeh    3 年前

    std::string 与常量字符串文字相去甚远。事实是 std::字符串 内部使用自己的 allocator 分配所需的内存空间,以便从其构造函数参数构造字符串。您可以访问C样式指针 std::字符串 的缓冲区通过 c_str 作用

    const char* ,实际上必须解释为 指向常量字符的指针 而不是 指向字符的常量指针 ,因为您可以递增和递减指针,这表明它是指向不可修改内存块的指针。当你写这样的东西时,你会做什么

    const char* str = "This is a test" 
    

    在内存中,有一个块,“这是一个测试”的所有字符都按顺序排列在那里,实际上这个块在 .rodata section 或 read-only section 最终对象文件的。

    定义一个名为 str 指向这个内存块,您可以通过以下方式修改指针本身 str++ 或 str-- 但不能修改其内容。因此,类似 *(str) = 'k' 会给你一个 Segmentation Fault 错误

    std::字符串 是一个C++类,它封装了您创建的字符串,并提供了对许多不同类方法的访问权限,在这些方法中,您可以了解字符串的不同属性和值。如前所述,您可以访问C样式 常量字符* 缓冲区 c_str ,通过访问字符串的大小 size ,等等。只是看看 here 了解更多信息。

    回到你的问题,我建议考虑以下内容:

    #include <iostream>
    #include <string>
    #include <array>
    
    int main()
    {
    
        std::array<char, 10> my_array = {
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'
        };
    
        std::string group_of_letters;
    
        for (const auto& ch: my_array)
            group_of_letters += ch;
    
        std::cout << group_of_letters;
    
        return 0;
    }