C++ Basics: Preserve a Character Array and Its Terminator
Use to_array to copy a built-in character array into std::array while retaining its full extent.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. You need a C++20-capable compiler and standard-library development headers, with g++ on PATH, plus Bash, a text editor, and the mktemp, rm, and rmdir utilities. No third-party library is required.
Keep the same terminal open. Stop if setup fails, before saving the source:
start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1Run the example
Save this as to-array-string-terminator-demo.cpp:
#include <array>
#include <iostream>
#include <string_view>
int main()
{
auto letters = std::to_array("cat");
letters[0] = 'b';
std::cout << "array size: " << letters.size() << '\n';
std::cout << "payload: " << std::string_view(letters.data(), letters.size() - 1) << '\n';
std::cout << "ends in null: " << std::boolalpha << (letters.back() == '\0') << '\n';
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic to-array-string-terminator-demo.cpp -o to-array-string-terminator-demo &&
./to-array-string-terminator-demoObserved output:
array size: 4
payload: bat
ends in null: trueRead the result
The string literal contains four characters including its terminating null. to_array copies all four into a mutable std::array<char, 4>. Editing the copy produces bat while preserving the final null.
Apply it carefully
The subtraction by one is appropriate here because this particular input is a null-terminated literal. An arbitrary character array may have no terminator; do not subtract blindly or pass an unterminated buffer to a C-string API. The string_view refers to letters, so it cannot outlive that array. to_array cannot recover an array extent from a pointer.
The C++ working draft describes the relevant rules. This example uses C++20; the current working draft also includes later additions.
Clean up
Remove only the source and executable created here, then return to the starting directory:
rm -- to-array-string-terminator-demo.cpp to-array-string-terminator-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.