Search code examples
c++arrayscstring

Initializing a Char*[]


Question is in the title, how do I initialize a char*[] and give values to it in C++, thank you.


Solution

  • Though you're probably aware, char*[] is an array of pointers to characters, and I would guess you want to store a number of strings. Initializing an array of such pointers is as simple as:

    char ** array = new char *[SIZE];
    

    ...or if you're allocating memory on the stack:

    char * array[SIZE];
    

    You would then probably want to fill the array with a loop such as:

    for(unsigned int i = 0; i < SIZE; i++){
        // str is likely to be an array of characters
        array[i] = str;
    }
    

    As noted in the comments for this answer, if you're allocating the array with new (dynamic allocation) remember to delete your array with:

    delete[] array;