Search code examples
c++pointer-to-pointer

Initializing and Navigating a char**


Okay, so consider this code:

char** pool = new char*[2];
pool[0] = new char[sizeof(char)*5];

As far as I know, this creates a pointer to an array of 2 char pointers. The second line then sets the first of these 2 char pointers to the first item in an array of 5 chars. Please correct me if I'm wrong.

If I'm not wrong:

  1. How would I go about initializing all of these chars?
  2. How would I change a specific char? For example, setting the last char to NULL in each array.

Solution

  • As far as I know, this creates a pointer to an array of 2 char pointers. [...]

    char** pool = new char*[2];
    

    No, that line creates a pointer to a pointer a character. The expression on the righthand side creates an array of 2 pointers to characters. You can initialize this a double pointer with an array of pointers, because the righthand side will decay into a double pointer.

    The second line then sets the first of these 2 char pointers to the first item in an array of 5 chars. [...]

    pool[0] = new char[sizeof(char)*5];
    

    What do you mean by "the first of these two char pointers". You're only assigning to one pointer on that line.

    How would I go about initializing all of these chars?

    By using a loop to iterate through the pointers and assigning valid memory to them.

    How would I change a specific char? For example, setting the last char to NULL in each array.

    for (char** p = pool; p != (pool + 2); ++p)
    {
        *p = new char[/* amount of chars */];
        (*p)[/* amount of chars */] = '\0';
    }
    

    But this is a complete mess. It would be significantly more easy to use a vector of strings:

    std::vector<std::string> pool;