std::array<char, size> null 终止了吗?

Is std::array<char, size> null terminated?

下面的代码片段安全吗?它调用了 std::string 的第四个构造函数,该构造函数接受一个指向空终止字符串的指针。问题是,我不确定下面的 word 是否以 null 结尾。是吗?

std::array<char, 4> word{'a', 'b', 'c', 'd'};

int main()
{
    std::string p = word.data();
    return 0;
}

Is std::array<char, size> null terminated?

它可以包含以空字符结尾的字符串。它不一定包含以空字符结尾的字符串。

std::array<char, 4> word{'a', 'b', 'c', 'd'};

此数组不包含以空字符结尾的字符串。您可以分辨出来,因为 none 个元素是空终止符。

std::string p = word.data();

此程序的行为未定义。

Is the following snippet of code safe?

没有


how to make word null terminated.

这是一个例子:

std::array<char, 5> word{'a', 'b', 'c', 'd'};

或者如果你想更明确一点:

std::array<char, 5> word{'a', 'b', 'c', 'd', '[=13=]'};

这个数组不是以 null 结尾的。使其以 null 终止的一种简单方法是从 string literal 初始化它,如下所示:

std::array<char, 5> a{"abcd"};

Is the following snippet of code safe?

没有。它正在调用 未定义的行为

It invoked std::string's fourth constructor that takes in a pointer to a null terminated string. The thing is, I'm not sure if word below is null terminated. Is it?

不,不是。

一个简单的修复,假设您不想以 null 终止数组,将使用不同的 std::string 构造函数,该构造函数将所需的长度作为参数,例如:

std::array<char, 4> word{'a', 'b', 'c', 'd'};

int main()
{
    std::string p(word.data(), word.size());
    // more generally:
    // std::string p(word.data(), desired_length);
    return 0;
}

或者,您可以使用不同的 std::string 构造函数代替迭代器,例如:

std::array<char, 4> word{'a', 'b', 'c', 'd'};

int main()
{
    std::string p(word.begin(), word.end());
    // more generally:
    // std::string p(word.begin(), word.begin() + desired_length);
    return 0;
}

无论哪种方式,您都不需要空终止符。

如果您的目标是在 std::array 中使用 null 终止字符串 初始化 std::string 但不是在 运行 范围内,您可以像这样使用 std::find

std::string p{std::begin(word), std::find(std::begin(word), std::end(word), '[=10=]')};

如果没有空终止符,它将初始化到第一个空终止符或数组末尾。