简体   繁体   English

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

[英]How to allocate memory to array of character pointers?

I want to allocate memory to the following array of char pointers: 我想将内存分配给以下char指针数组:

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

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

Following does not work: 以下操作无效:

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

What is the way to allocate memory for an array of strings? 为字符串数组分配内存的方法是什么?

In C++ there are more ways to initialize a string array. 在C ++中,有更多方法可以初始化字符串数组。 You could just use the string class. 您可以只使用string类。

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

For a char array in C , you can use malloc . 对于C的char数组,可以使用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); 

There is mixing up of C and C++ syntax and not sure if you are trying in C or C++. C和C ++语法混合使用,不确定是否要使用C或C ++。 If you are trying with C++, below is a safe way to go. 如果您尝试使用C ++,则以下是一种安全的方法。

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

For completely dynamic one std::vector can be used. 对于完全动态的,可以使用一个std::vector

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

May be below is what you are finding: 可能是您找到的以下内容:

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
}

But working with char* is very trouble. 但是使用char*很难。 I recommend you to use string library in c++ to store and manipulation with strings. 我建议您在c ++中使用string库来存储和处理字符串。

Since this is a C++ question, I'd advise an idiomatic way to handle a fixed/variable collection of text: std::array or std::vector and std::string . 由于这是一个C ++问题,我建议采用一种惯用的方式来处理文本的固定/可变集合: std::arraystd::vectorstd::string

What is the way to allocate memory for an array of strings? 为字符串数组分配内存的方法是什么?

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

or 要么

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

Then, you can manipulate strings in a intuitive way, without having to handle memory by hand: 然后,您可以直观的方式操作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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM