Search code examples
c++structc++17initializer-listconstruct

How to initialize char[] in a struct with constexpr char[] using initializer list?


I have a struct like:

constexpr char defaultName[6] = "Hello";

struct MyStruct{
   char name[6];
   int val;
};

Now I want to initialize the struct using initializer list as following:

MyStruct structObj{defaultName, 0};

However, this doesn't work. How do I initialize the char array in initializer using defaultName?

I used MyStruct structObj{defaultName, 0}; but this doesn't work. I know I can do {"Hello", 0} but I would like to use constexpr. Also, strcpy works but just wanted to know if there is a way to use the defaultName in initializer list.

Note: The struct is defined in a common library C header which is used by the C++ code so I can't update the struct definition.


Solution

  • Arrays aren't copiable normally, but std::array is

    constexpr std::array<char,6> defaultName {'H', 'e', 'l', 'l', 'o', '\0'};
    
    struct MyStruct{
       std::array<char,6> name;
       int val;
    };
    
    MyStruct structObj{defaultName, 0};
    

    If you can't update the struct, then use a default struct instead:

    struct MyStruct{
       char name[6];
       int val;
    };
    constexpr MyStruct defaultStruct{"Hello",0};
    
    MyStruct structObj(defaultStruct);