将元素放入链表后,当我想访问它们时,我遇到了分割错误。我尝试从头部插入(头部是tete(,在阅读元素时,我仅在该函数中没有问题
以下是导致分段错误错误的行:
if((p->ID.num)>(p2->ID.num))
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <conio.h>
typedef struct identifiant//identifiant
{
char section[50];
int num;
}identifiant;
typedef struct Date //DATE
{
int jj;
int mm;
int an;
}Date;
typedef struct notes
{
float note;
struct notes* nnext;
}notes;
typedef struct LTE
{
identifiant ID;
char Nom[25];
char Prenom[25];
Date Date_naissance;
notes* Tnotes;
float Moy;
struct LTE* next;
}LTE;
typedef struct coefs
{
int coef;
struct coefs* next;
}coefs;
coefs* COEF;
LTE* tete;
int main()
{ int NE,NN;
LTE* p;
LTE* n;
LTE* m;
coefs* q;
int i,x;
x=0;
NE = Saisie_NE();
NN = Saisie_NN();
{
tete=(LTE*)malloc(sizeof(LTE));
tete->next=0 ;
Saisie_E(1,tete,NN);
for(i=2;i<=NE;i++)
{
LTE* tmp=(LTE*)malloc(sizeof(LTE));
Saisie_E(i,tmp,NN);
tmp->next=tete;
tete=tmp;
}
}....
//remplir tabeleau des coefs
{
COEF=(coefs*)malloc(sizeof(coefs));
COEF->next=0 ;
q=COEF;
for(i=0;i<NN;i++){
Saisie_coef(i+1,q,NN,&x);
coefs* tmp=(coefs*)malloc(sizeof(coefs));
q->next=tmp;
q=q->next;
}
q->next=0;
}
//everything works fine until the this function↓↓↓
{
p=tete;
Trier(p,NE);
}
//here is the functuion ty guys sorry for bad presentation
void Trier(LTE* p,int NE)
{
int tr,i;
LTE* q;
LTE* p1;
LTE* p2;
p1=p;
i=0;
while(tr!=1)
{ tr=1;
p=p1;
for(i=0;i<NE;i++)
{ p2=p->next;
//here is the segment fault error
if((p->ID.num)>(p2->ID.num))
{q=p->next->next;
p->next->next=p;
p->next=q;
tr=0;
}
p=p->next;
}
}
问题出在下面的循环中。在循环迭代期间,当i == (NE-1)
时,p
将指向最后一个节点,p->next
将为 NULL,分配给p2
。因此,访问p2->ID.num
会导致分段错误。
您可以添加检查p2!=NULL
或修改循环逻辑以防止这种情况发生。
for(i=0;i<NE;i++)
{ p2=p->next; /* ==> When p becomes the last node, p2 will become NULL */
//here is the segment fault error
if((p->ID.num)>(p2->ID.num))
{q=p->next->next;
p->next->next=p;
p->next=q;
tr=0;
}
p=p->next;
}