简体   繁体   中英

How to initialize a std::array<char, N> with a string literal omitting the trailing '\0'

I have a file structure where fixed length strings have no trailing zero. How to initialize fields as std::array without trailing zero:

#pragma pack(push, 1)
struct Data {
    // Compiles, but it has an undesired '\0':
    std::array<char, 6> undesired_number{"12345"};
    // Does not compile:
    std::array<char, 5> number{"12345"}; // stripping '\0'
};
#pragma pack(pop)

Making a helper function

template <std::size_t N, std::size_t ... Is>
constexpr std::array<char, N - 1>
to_array(const char (&a)[N], std::index_sequence<Is...>)
{
    return {{a[Is]...}};
}

template <std::size_t N>
constexpr std::array<char, N - 1> to_array(const char (&a)[N])
{
    return to_array(a, std::make_index_sequence<N - 1>());
}

And then

struct Data {
    std::array<char, 5> number{to_array("12345")}; // stripping '\0'
};

Demo

A string literal is NUL-terminated, in C++ (unlike C) you cannot take it off by providing a Length - 1 size; therefore it cannot be done directly , also considering that array internally is a T[N] .

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