简体   繁体   中英

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
}

You need to terminate it:

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

As you should be using nullptr in C++, not NULL which is for C code.

Additionally, use std::vector and std::string instead of this mess:

std::vector<std::string> myArray = { "Hello", "World" };

for (auto&& str : myArray) {
  // ... str is your string reference
} 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM