Hello I have an Exercice where they give me this struct:
enum Sexe { INCONNUE=0, MASCULIN=1, FEMININ=2};
struct Personne {
int numero;
char nom[10];
Sexe sexe;
};
And I need to make a pointer and assign values to it. So I did this function:
void Init() {
Personne *p;
string sexe;
Sexe s;
string n;
string nom;
char name[10];
cout << "Choisissez le numero de la personne";
cin >> n;
cout << "Choisissez le nom de la personne";
cin >> nom;
cout << "Choisissez le sexe de la personne";
cin >> sexe;
for (int i = 0; i < nom.length(); i++){
name[i] = nom[i];
}
if (sexe == "1" || sexe == "Masculin" || sexe == "masculin" || sexe == "MASCULIN") {
s = Sexe::MASCULIN;
} else if (sexe == "1" || sexe == "Feminin" || sexe == "feminin" || sexe == "FEMININ") {
s = Sexe::FEMININ;
} else {
s = Sexe::INCONNUE;
}
Personne join_p{stoi(n),name,s};
p = &join_p;
}
But I have this error and I don't undestand why and how to fix it:
error: array must be initialized with a brace-enclosed initializer
Personne join_p{stoi(n),name,s};
I tried to put the brackets at different places like they where saying in my lessons or other websites but it doesn't want to work
In this declaration
Personne join_p{stoi(n),name,s};
the data member of the structure Personne
is declared like
char nom[10];
that is it is an array,
But the array name
used as an initializer is implicitly converted to a pointer to its first element.
So you are trying to initialize an array with a pointer.
You may not initialize an array with a pointer. You need to copy the array name
into the array join_p.nom
.
Pay attention to that the array name
does not contain a string but it seems that the data member nom
must contain a string.
In any case this loop
for (int i = 0; i < nom.length(); i++){
name[i] = nom[i];
}
is unsafe because you can write outside the array name
.
It would be better that initially the data member nom
of the structure had the type std::string
.
Also these statements
Personne join_p{stoi(n),name,s};
p = &join_p;
do not make a great sense because the pointer p
is not used anywhere within or outside the function except this assignment.