Потеря элементов при печати очереди в C - PullRequest
0 голосов
/ 27 апреля 2019

Это мой код:

typedef struct noeud{
    int x;
    struct noeud* suivant;
} noeud;

typedef noeud* file;

file enfiler(file f, int val){
    file nv = (file) malloc(sizeof(noeud));
    nv->x = val; nv->suivant = NULL;

    if (f == NULL)
      f = nv;
    else {
      file tmp = f;
      while(tmp->suivant != NULL) tmp = tmp->suivant;
      tmp->suivant = nv;
    }
    return f;
}

file defiler(file f){//removing an element of the FIFO data structure
  if (f == NULL)
    return f;
  else {
    file tmp = f;
    f = f->suivant;//receiving address of next node, the last one points to NULL
    free(tmp);
    return f;
  }
}

int tete(file f){
  return f->x;//getting the element of the head
}

void init(file * f) {
  *f = NULL;
}

void affiche(file f){//print data structure's elements
  if (f == NULL)
    printf("File vide.\n");
  else {//emptying the FIFO data structure into tmp to access elements
    file tmp; init(&tmp);
    while(f != NULL){
        tmp = enfiler(tmp, tete(f));
        f = defiler(f);
    }
    int i = 0;
    while(tmp != NULL) {//emptying tmp to original f
        printf("F[%d] = %d\n", ++i, tete(tmp));
        f = enfiler(f, tete(tmp));
        tmp = defiler(tmp);
    }
  }
}

Это мой ввод:

file f; init(&f);//initializing f to NULL
f = enfiler(f, 6);//adding elements
f = enfiler(f, 45); 
f = enfiler(f, 78);
f = enfiler(f, 5);
affiche(f);
affiche(f);
affiche(f);

Это вывод:

F [1] = 6
F [2] = 45
F [3] = 78
F [4] = 5
F [1] = 78
F [2] = 5
F [1] = 2036736 // это случайное значение

С каждым void affiche(file f) потерялись две головы, я пересмотрел функцию file defiler(file f), но не могу найти ошибку, file enfiler(file f, int x) тоже хорошо.

Спасибо за ваше время!

1 Ответ

1 голос
/ 27 апреля 2019

Чтобы отменить вывод, вы создаете и перестраиваете свою очередь.Ваша реконструкция не повторно связывает те же узлы.Вместо этого вы просто берете значения и создаете два совершенно новых списка.Это означает, что локальная переменная f в afficher обычно будет отличаться при вводе и выходе из afficher.Вы можете проверить это, добавив следующие операторы:

void affiche(noeud *f)
{
    printf("entree: %p\n", f);

    // body of afficher function    

    printf("sortie: %p\n", f);
}

Проблема в том, что f в вызывающей функции не обновляется.Это может указывать на недавно освобожденную память или на другой действительный узел.Другими словами, ваш список, скорее всего, будет поврежден.

Самый простой способ исправить это - вернуть новую голову, как в enfiler и defiler.

...