我在功能“trier”中做了什么,它改变了病人的名字?

问题描述 投票:0回答:1

关于为患者创建链接列表的练习,然后按名称排列。我想换掉他们的名字;似乎我所做的不起作用。

我试图把前面的指针“prec”并比较下一个指针“ptr”的名称然后我试图在名为“echangedeChaine”的函数中交换它们的名字

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

struct patient{
    int cin;
    char nom[8];
    char prenom[8];
    int annee;
    struct patient *suivant;
};

struct patient *tete=NULL;

void creationdePatient(){
    struct patient* ptr;
    char rep;

    ptr = malloc(sizeof(struct patient));
    tete =ptr;
    printf("Saisir Numero de Cin de Nouveau Patient: ");
    scanf("%d",&tete->cin);
    printf("Saisir Nom de Patient: ");
    scanf("%8s",&tete->nom);
    printf("Saisir prenom de Patient: ");
    scanf("%8s",&tete->prenom);
    tete->suivant = NULL;
    printf("\nVoulez vous Saisir un autre Patient ?: (O,N): \n");
    scanf(" %c",&rep);

    while(toupper(rep)=='O'){
        ptr = malloc(sizeof(struct patient));
        printf("Saisir Numero de Cin de Nouveau Patient: ");
        scanf("%d",&ptr->cin);
        printf("Saisir Nom de Patient: ");
        scanf("%8s",&ptr->nom);
        printf("Saisir prenom de Patient: ");
        scanf("%8s",&ptr->prenom);
        ptr->suivant = tete;
        tete=ptr;
        printf("\nVoulez vous Saisir un autre Patient ?: (O,N): \n");
        scanf(" %c",&rep);
    }
}

void echangedeChaine(char x[8] , char y[8]){
    char temp[8];
    strcpy(temp,y);
    strcpy(y,x);
    strcpy(x,temp);
}


void printtList(){
    struct patient *temp = tete;

    while(temp!=NULL){
        printf("Cin: %d | Nom:%s | Prenom: %s\n", temp->cin, temp->nom, temp->prenom);
        temp=temp->suivant;
    }
}


void trier(){
    struct patient *ptr = tete;
    struct patient*prec;
    int echange=0;
    do{
        while(ptr!=NULL){
            prec=ptr;
            ptr=ptr->suivant;
            if(strcmp(prec->nom,ptr->nom)<0){
                echangedeChaine(prec->nom,ptr->nom);
                echange=1;
            }
        }
    }while(echange==1);
}

int main()
{
   creationdePatient();
   printtList();
   trier();
   printtList();
}

在我尝试执行它之后,它似乎无效。

c
1个回答
1
投票

您的代码有几个问题,包括(但不一定限于):

  1. 您在trier()中的代码将取消引用最后一个元素的NULL指针 - 因为它的suivant为NULL,并且您正在执行: ptr = ptr->suivant; if(strcmp(prec->nom,ptr->nom) < 0) { ... }
  2. 我认为你试图按错误的顺序排序:当strcmp(prec->nom,ptr->nom)为阴性时,这意味着第一个病人的名字在词典上比下面的病人姓名更早 - 在这种情况下,他们不应该被交换。

PS - 对于那些不懂法语的人来说,这里有一个关于OP计划的小词汇表......

tete =头 suivant =下一个 nom =姓氏/姓氏 prenom =第一个/给定名称 交换=改变(或替换) chaine = list(或cain)

© www.soinside.com 2019 - 2024. All rights reserved.