Search code examples
c++arraysnullc-stringsstring-literals

C++ array of strings terminator


I am new to C++, I know that character arrays/char*(c-strings) terminate with a Null byte, but is it the same for string arrays/char**?

My main question is: how can i know if I reached the end of a char** variable? Will the following code work?

#include <cstddef>

char** myArray={"Hello", "World"};

for(char** str = myArray; *str != NULL; str++) {
  //do Something
}

Solution

  • For starters this declaration

    char** myArray={"Hello", "World"};
    

    does not make a sense, You may not initialize a scalar object with a braced-list with more than one expression.

    It seems you mean a declaration of an array

    const char* myArray[] ={ "Hello", "World"};
    

    In this case the for loop can look like

    for( const char** str = myArray; *str != NULL; str++) {
      //do Something
    }
    

    But the array does not have an element with a sentinel value. So this condition in the for loop

    *str != NULL
    

    results in undefined behavior.

    You could rewrite the loop for example like

    for( const char** str = myArray; str != myArray + sizeof( myArray ) / sizeof( *myArray ); str++) {
      //do Something
    }
    

    Or instead of the expression with the sizeof operator you could use the standard function std::size introduced in the C++ 17 Standard.

    Otherwise the initial loop would be correct if the array is declared like

    const char* myArray[] ={ "Hello", "World", nullptr };
    

    In this case the third element will satisfy the condition of the loop.