Search code examples
c++initializationpointer-to-pointer

Declaration and initialize pointer-to-pointer char-array


Concerning a pointer to pointer I wonder if its ok with the following:

    char** _charPp = new char*[10];

     for (int i = 0; i < 10; i++)
    ´   _charPp[i] = new char[100];

That is - if I want a pointer to pointer that points to 10 char-arrays.

The question - is this ok now or do I have to make some kind of initializing of every char-arrays? Then - how do I do that?

I will later on in the program fill these arrays with certain chars but i suspect that the arrays should be initialized with values before such as "0"


Solution

  • Yes, it looks pretty much suitable,

    int arraySizeX = 100;
    int arraySizeY = 100;
    char** array2d = new char*[arraySizeX] // you've just allocated memory that
                                           // holds 100 * 4 (average) bytes
    for(int i = 0; i < arraySizeX; ++i)
    {
        array2d[i] = new char[arraySizeY] // you've just allocated a chunk that 
                                           //holds 100 char values. It is 100 * 1 (average) bytes
        memset(array2d[i], 0, arraySizeY) // to make every element NULL
    }
    

    I will later on in the program fill these arrays with certain chars but i suspect that the arrays should be initialized with values before such as "0"

    No, there's no "default value" in C++. You need to assign 0 to the pointer to make it null, or use memset() to do it with arrays.