2

With this code:

struct Structure {
    int a;
    char b[4];
};

void function() {
    int a = 3;
    char b[] = {'a', 'b', 'c', 'd'};
}

Can I initialize Structure with the values of a and b using aggregate initialization?
I tried Structure{a, b}, however that gives me the error cannot initialize an array element of type 'char' with an lvalue of type 'char [4]'

user1000039
  • 725
  • 1
  • 6
  • 16
  • if you change both `char b[]` by `std::array`, yes. [Demo](http://coliru.stacked-crooked.com/a/8ac7cfe90b9a75e0) – Jarod42 Mar 07 '17 at 17:43

2 Answers2

0
struct S {
    int a;
    char b[4];
};

int main() {
    S s = { 1, {2,3,4,5} };
}

Edit: Just re-read your question - no, you can't do that. You can't initialise an array with another array.

0

If you are familiar with parameter-pack-expansion I think you can, like this:

struct Structure {
    int a;
    char b[4];
};

template< typename... I, typename... C>
void function(I... a, C... b) {
    Structure s = { a..., b... }; // <- here -> a = 1 and b = 'a','b','c','d'
    std::cout << s.a << '\n';
    for( char chr : s.b ) std::cout << chr << ' ';
}

int main(){
    function( 1, 'a','b','c','d' );
}

The output:

1
a b c d
Shakiba Moshiri
  • 13,741
  • 2
  • 20
  • 35