1

Avec ce code:C++ - initialiser un élément de matrice à l'initialisation globale

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

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

je peux initialiser Structure avec les valeurs de a et b utilisant l'initialisation globale?
J'ai essayé Structure{a, b}, mais qui me donne l'erreur cannot initialize an array element of type 'char' with an lvalue of type 'char [4]'

+0

si vous changer à la fois 'char b [] ' par 'std :: array ', oui. [Démo] (http://coliru.stacked-crooked.com/a/8ac7cfe90b9a75e0) – Jarod42

Répondre

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

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

Edit: Il suffit de relire votre question - non, vous ne pouvez pas faire cela. Vous ne pouvez pas initialiser un tableau avec un autre tableau.

0

Si vous êtes familier avec pack-extension paramètreJe pense que vous pouvez, comme ceci:

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'); 
} 

La sortie:

1 
a b c d