[英]C++: Store contents of text file into 2D array as strings (trouble with null terminator?)
[英]C++ array of strings terminator
我是 C++ 的新手,我知道字符數組/char*(c-strings) 以 Null 字節結尾,但字符串數組/char** 是否相同?
我的主要問題是:我怎么知道我是否到達了 char** 變量的末尾? 下面的代碼會起作用嗎?
#include <cstddef>
char** myArray={"Hello", "World"};
for(char** str = myArray; *str != NULL; str++) {
//do Something
}
您需要終止它:
const char** myArray={"Hello", "World", nullptr};
因為您應該在 C++ 中使用nullptr
,而不是NULL
,它適用於 C 代碼。
此外,使用std::vector
和std::string
代替這種混亂:
std::vector<std::string> myArray = { "Hello", "World" };
for (auto&& str : myArray) {
// ... str is your string reference
}
對於初學者來說,這個聲明
char** myArray={"Hello", "World"};
沒有意義,您不能使用帶有多個表達式的花括號列表初始化標量 object。
看來你的意思是一個數組的聲明
const char* myArray[] ={ "Hello", "World"};
在這種情況下,for 循環看起來像
for( const char** str = myArray; *str != NULL; str++) {
//do Something
}
但是該數組沒有具有標記值的元素。 所以for循環中的這個條件
*str != NULL
導致未定義的行為。
您可以重寫循環,例如
for( const char** str = myArray; str != myArray + sizeof( myArray ) / sizeof( *myArray ); str++) {
//do Something
}
或者,您可以使用 C++ 17 標准中引入的標准 function std::size
來代替帶有sizeof
運算符的表達式。
否則,如果數組聲明為
const char* myArray[] ={ "Hello", "World", nullptr };
在這種情況下,第三個元素將滿足循環的條件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.