Aquarius_Girl
Aquarius_Girl

Reputation: 22906

How to allocate memory to array of character pointers?

I want to allocate memory to the following array of char pointers:

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?

Upvotes: 0

Views: 3547

Answers (4)

Vinay P
Vinay P

Reputation: 635

There is mixing up of C and C++ syntax and not sure if you are trying in C or C++. If you are trying with C++, below is a safe way to go.

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

For completely dynamic one std::vector can be used.

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

Upvotes: 3

YSC
YSC

Reputation: 40070

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.

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[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.

Upvotes: 0

AndrejH
AndrejH

Reputation: 2109

In C++ there are more ways to initialize a string array. You could just use the string class.

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

For a char array in C, you can use 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); 

Upvotes: 3

TaQuangTu
TaQuangTu

Reputation: 2343

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. I recommend you to use string library in c++ to store and manipulation with strings.

Upvotes: 2

Related Questions