[英]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.