在C中打印队列时丢失元素

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

这是我的代码:

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)也没关系。

感谢您的时间!

c queue fifo
1个回答
1
投票

为了反转输出,您构造并重新构造队列。您的重建不会重新链接相同的节点。相反,您只需获取值并创建两个全新的列表。这意味着f中的局部变量afficher在进入和离开afficher之后通常会有所不同。您可以通过添加以下语句来测试它:

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

    // body of afficher function    

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

问题是你的调用函数中的f没有更新。它可以指向最近的free'd内存或另一个有效节点。换句话说,您的列表可能已损坏。

解决这个问题的最简单方法是返回新头,如enfilerdefiler

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