如何将内存分配给字符指针数组?

时间:2018-06-04 10:13:40

标签: c++ arrays pointers

我想将内存分配给以下char指针数组:

char *arr[5] =
    {
        "abc",
        "def",
        "ghi",
        "jkl"
    };

    for (int i = 0; i < 4; i++)
        std::cout << "\nprinting arr: " << arr[i];

以下不起作用:

char *dynamic_arr[5] = new char[5];

为字符串数组分配内存的方法是什么?

4 个答案:

答案 0 :(得分:2)

在C ++中,有more个方法来初始化字符串数组。你可以使用string类。

string arr[4] = {"one", "two", "three", "four"};

对于C中的字符数组,您可以使用malloc

char *arr[5];
int len = 10; // the length of char array
for (int i = 0; i < 5; i++)
    arr[i] = (char *) malloc(sizeof(char) * len); 

答案 1 :(得分:2)

C和C ++语法混合在一起,不确定您是否尝试使用C或C ++。如果你正在尝试使用C ++,下面是一个安全的方法。

std::array<std::string, 10> array {};

对于完全动态的,可以使用std::vector

std::vector<std::string> array;

答案 2 :(得分:1)

您可能会发现以下内容:

char **dynamic_arr = new char*[5]; //5 is length of your string array
for(int i =0;i<5;i++)
{
    dynamic_arr[i] = new char[100]; //100 is length of each string
}

但与char*合作非常麻烦。我建议你在c ++中使用string库来存储和操作字符串。

答案 3 :(得分:0)

由于这是一个C ++问题,我建议采用惯用的方式来处理固定/可变的文本集合:std::arraystd::vectorstd::string

  

为字符串数组分配内存的方法是什么?

// If you have a fixed collection
std::array<std::string, 4> /* const*/ strings = {
    "abc", "def", "ghi", "jkl"
};

// if you want to add or remove strings from the collection
std::vector<std::string> /* const*/ strings = {
    "abc", "def", "ghi", "jkl"
};

然后,您可以直观地操作strings,而无需手动处理内存:

strings[2] = "new value for the string";
if (strings[3] == strings[2]) { /* ... */ } // compare the text of the third and fourth strings
auto pos = strings[0].find("a");
// etc.
相关问题