I try to add a char array in my linked list using strcpy but in this case I have segmentation fault. I know how to allocate the memory for int but have trouble with char array. Do we need to use malloc especially for each char array of the linked list? This is my code :
typedef struct Avion Avion;
struct Avion
{
char *NomAvion;
char *NomCompanie;
int Carburant;
int place;
Avion *suivant;
};
typedef struct Liste Liste;
struct Liste
{
Avion *premier;
};
void AjouterUnAvion(Liste *liste)
{
char nomAvion1[20] = "defaultNomAvion";
char nomCompanie1[20] = "defaultNomCompanie" ;
scanf("%s",nomAvion1);
scanf("%s",nomCompanie1);
if(liste == NULL)
{
exit(EXIT_FAILURE);
}
Avion *nouvAv = malloc(sizeof(*nouvAv));
strcpy(nouvAv->NomAvion,nomAvion1);
strcpy(nouvAv->NomCompanie,nomCompanie1);
Avion *current = malloc(sizeof(*current));
current = liste->premier;
while(current->suivant != NULL)
{
current = current->suivant;
}
current->suivant = nouvAv;
}
int main()
{
Liste *liste = initialisationListe();
AjouterUnAvion(liste);
return 0;
}
CodePudding user response:
Elaborating more about the comment I've just made, when you called Avion *nouvAv = malloc(sizeof(*nouvAv));
, it does not allocate space (I believe you want 20 chars for name and company, right?) for the pointers inside the structure. You could:
- make those struct members fixed size - like
char nom_avion[20]
- allocate space for each of them, calling malloc (or any other function that allocates enough memory for you)
- make it point to existing and allocated permanent arrays with equals operator (be aware, when you make it inside a function for instance, the memory can be cleared and then the pointer would be pointing to nowhere)