1

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.

5
  • 1
    any reason why str is not a std::string? Commented May 6, 2020 at 16:18
  • 2
    The standard way to handle strings in C++ is to use 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? Commented May 6, 2020 at 16:18
  • 3
    "Why doesn't modern C ++ accept the (1) form?" Because modern C++ (and old C++) uses std::string instead of char arrays. Commented May 6, 2020 at 16:20
  • Your (1) code does work in clang-cl and MSVC (the latter with /std:c++latest - in order to use the designated initializers). Commented May 6, 2020 at 16:21
  • The code I chose to put in this question has been oversimplified. My actual code involves a char[] member within a union within a structure. I can't put std::string inside union. Commented May 6, 2020 at 16:42

1 Answer 1

1

just replace

S s1={.x=12, .str = "Hello2"};

by the 'C' initialization form

S s1={12, "Hello2"};

or as said in remarks use a std::string which is a most elegant, concise and practical way than an array of char for a string, and you will able to use the 'C++' initialization form you wanted

Sign up to request clarification or add additional context in comments.

3 Comments

But It requires to follow the order of the member fields. It is possible to use designators (member names) in some way?
@Berk7871 yes you have to take care of the order as in C, no you cannot use designators because only the C++ form allows that
Ok. I am curious as to why the C ++ Committee did not include this simple feature (allowing the use of designators to initialize a char[] from a literal string) in the language.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.