Search code examples
c++stringcharcalloc

C++ string char** translation


How can I make an array of n strings using char**?

char** lit;
*lit = (char*)calloc(this->nr_param, sizeof(char*));
for(int i = 0; i < this->nr_param; i++)
      lit[i] = (char*) calloc(this->nr_param, sizeof(char));    

Is this the way? If so, how can i access elements? Lets say my array will contain the following elements: aaab, abba, baab;

I want this structure:

lit[0] = "aaab";
lit[1] = "abba";
lit[2] = "baab"; 

It's ok how I declared them?


Solution

  • Like this:

    // allocate memory for n char pointers dynamically.
    char ** lit = static_cast<char**>(::operator new(n * sizeof(char*)));
    
    for (unsigned int i = 0; i != n; ++i)
    {
        lit[i] = static_cast<char*>(::operator new(length_of_string_i)); // #1
        // populate lit[i] with data
    }
    

    You need some method of determining the length of the ith string, which you need to paste appropriately in the line marked #1. Note that sizeof(char) == 1, so you don't need to multiply anything in the inner allocation. (You can use std::malloc instead of ::operator new if you prefer, but then you have to #include <cstdlib>.) Don't forget to clean up when you're done!

    This is of course only the literal translation of what you asked for. In C++, you would usually prefer object creation over raw memory allocation, which looks like this:

    // construct n char pointers dynamically
    char ** lit = new char*[n];
    
    for (unsigned int i = 0; i != n; ++i)
    {
        lit[i] = new char[length_of_string_i];
        // populate lit[i] with data
    }
    

    But you should seriously never use array-new. It's not a good concept, and rarely good C++.

    So, you shouldn't be doing this at all, and instead you should use:

    std::vector<std::string> lit(n);