简体   繁体   中英

Initialize char arrays from string literal

I have a struct with char array inside it, however I can't find a decent way to initialize it if string becomes longer.

struct T
{
    char id[4];
};

T t{ 'a','b', 'c','d'}; // case 1: OK

T t{"abcd"};   // case 2: ERROR, "abcd" size is 5, too long for id

I get below error:

   error: initializer-string for array of chars is too long [-fpermissive]
     T t{"abcd"};

The reason is that string literal "abcd" contains null terminator, so the size is 5.

This syntax is allowed C99 string literals , how can I work around in C++11?

You're out of luck. If you can't change T then there is no workaround unless you give up on direct initialization. You'll have to use T t{'a', 'b', 'c'}; etc. This is because T is an aggregate, so the only form of initialization is to pass actual initializers for each element.

Of course you can write a function, eg:

T t = T_from_literal("abcdefgh...");

where that function uses std::copy or similar to copy the characters into a T t; and returns by value, taking advantage of copy elision.

You may mind the '\\0' char in the end of the string when initializing, so you always have to take one more char to make it work:

struct T
{
    char id[5];
};

See this example

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