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

How to allocate memory to array of character pointers?

本文关键字:分配 内存 数组 指针 字符      更新时间:2023-10-16

我想为以下字符指针数组分配内存:

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];

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

在C++中,有更多的方法可以初始化字符串数组。您可以只使用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); 

C和 C++ 语法混淆,不确定您是在尝试使用 C 还是C++。如果您正在尝试使用C++,以下是一种安全的方法。

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

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

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

可能下面是你找到的:

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库来存储和操作字符串。

由于这是一个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.