【问题标题】:Getting segmentation fault when sorting an linked list对链表进行排序时出现分段错误
【发布时间】:2018-06-04 00:55:12
【问题描述】:

所以这是我的排序功能,我不是交换链表中的信息,只是交换下一个节点的指针。我有一个类似的功能,可以按完美运行的汽车价格排序,当我使用按汽车年份排序时,我得到分段错误 11。

void ordenaCrescenteAno(ELEMCAR *iniLista){
  ELEMCAR *aux1 = NULL;
  ELEMCAR *aux2 = NULL;
  ELEMCAR *maior = NULL;
  ELEMCAR *troca = NULL;

  if(iniLista == NULL){
    printf("Lista Vazia\n");
    return;
  }

  for(aux1 = iniLista; aux1 != NULL; aux1 = aux1 -> seguinte){
    maior = aux1;
    for(aux2 = aux1; aux2 != NULL; aux2 = aux2 -> seguinte){
       if(aux2->info.ano > maior->info.ano){
          maior = aux2;
       }
    }
    if(maior != aux1){
      troca->seguinte = aux1->seguinte;
      aux1->seguinte = maior->seguinte;
      maior->seguinte = troca->seguinte;
    }

 }
}

我将把链表的详细信息放在这里:

typedef struct carro{
    char matricula[7];
    char marca[30];
    char modelo[30];
    int ano;
    char classe[30];
    float preco;
    char combustivel[10];
    int dataInspecao;
    int dataRevisao;
    char observacoes[100];
    int estado;
}CARINFO;

typedef struct CarElem{
    CARINFO info;
    struct CarElem *seguinte;
}ELEMCAR;

我做错了什么?我想不通,因为我有一个类似的功能,但我是按“preco”变量排序的。

【问题讨论】:

    标签: c sorting pointers linked-list


    【解决方案1】:

    troca 被初始化为 null 所以troca->sequinte 会出错

    改用这个

    struct CarElem *troca; replace troca definition
    
    troca = aux1->sequinte; replace troca->sequinte line with this
    maior->sequinte = troca; remove ->sequinte from troca
    

    我意识到上面的代码 sn-p 有问题。

    在你的交换部分

    if (maior != aux1)
    {
      CARINFO carswap = aux1->info; // Copy the info into a temporary variable
      aux1->info = maior->info;     // Move info from maior to aux1
      maior->info = carswap;        // Move info from temporary variable to maior
    }
    

    希望这段代码 sn-p 能满足您的要求

    【讨论】:

    • 通过这样做,当我在排序后尝试打印链接列表中的汽车时,我只得到一辆车,而我的链接列表中有 3 辆,帮助?