Search code examples
c++dynamiccharacter-arrays

Is it possible to have a dynamically populating Array of char* in C++


I have a situation like this.

declare array of char*;
switch(id)
{
case 1:
    add 4 words in array
case 2:
    add 2 words in array
default:
    add 1 word in array
}

use array here;

Is it possible to do such thing in C++. I tried doing that but it is not working for me.


Solution

  • Yes. For clean, easy-to-understand, correct, exception-safe code, use vector and string:

    std::vector<std::string> v;
    
    switch (id)
    {
    case 1:
        v.push_back("a");
        v.push_back("b");
        v.push_back("c");
        v.push_back("d");
        break;
    
    case 2:
        v.push_back("a");
        v.push_back("b");
        break;
    
    default:
        v.push_back("a");
    }
    
    // Use the strings in v; for example, using a C++11 lambda expression:
    std::for_each(begin(v), end(v), [](std::string const& s)
    {
        std::cout << s << std::endl;
    });
    
    // Or using a for loop:
    for (std::vector<std::string>::const_iterator it(v.begin()); it != v.end(); ++it)
    {
        std::cout << *it << std::endl;
    }
    

    Of course, you can accomplish similar results using manual dynamic allocation and cleanup of both the array and the C strings, but to do so and to ensure that the code is correct and exception-safe is more difficult and would require substantially more code.