I'm trying to understand struct initialization in C++, in special char array member:
struct S {
int x;
char str[16];
};
// (1) This would be the desired way: simple and compact, but doesn't work
S s1={.x=12, .str = "Hello2"};
// (2) Instead, this appears the correct way to do, but it is ugly and cumbersome for bigger strings
S s2={.x=25, .str = {'H','e','l','l','o', '1'}};
// (3) This works too, easy to type, but uses 2 lines and a additional function (strcpy)
S s3={.x=12};
strcpy(s3.str, "Hello3");
Why doesn't modern C ++ accept the (1) form? It would be the most elegant, concise and practical way. Considering (2) and (3), is there a better way to do this?
EDIT 1: The code I choose to put in this question has been oversimplified. My actual code involves a char[] member within a union within a structure. Then, std::string is not an option.
stris not astd::string?std::string. What is the actual problem this structure is supposed to solve? Why do you need a fixed-size array? And if you can't get rid of the array, why not create a constructor which initializes the array?std::stringinstead of char arrays.clang-clandMSVC(the latter with/std:c++latest- in order to use the designated initializers).