【发布时间】:2021-12-27 13:52:13
【问题描述】:
我尝试使用 strcpy 在我的链表中添加一个 char 数组,但在这种情况下我遇到了分段错误。我知道如何为 int 分配内存,但对 char 数组有问题。我们是否需要特别为链表的每个字符数组使用 malloc?这是我的代码:
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;
}
【问题讨论】:
-
结构 Avion 中有两个指针。您应该为它们分配空间(以便使用
strcpy)或使其指向您之前读取的数组。 -
考虑使用
nouvAv->NomAvion = strdup(nomAvion1);你不能存储指向nomAvion1的指针,因为它会超出范围和寿命。
标签: c linked-list