【问题标题】:Losing elements while printing a queue in C在 C 中打印队列时丢失元素
【发布时间】:2019-04-27 17:50:32
【问题描述】:

这是我的代码:

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)也可以。

感谢您的宝贵时间!

【问题讨论】:

  • 能否分享enfiler(...)的代码?
  • 完成!不应该跳过那个。
  • 如果我很理解void init(file * f) { *f = NULL; }
  • 是的,就是这样!
  • 我编辑了您的问题以添加它,并修复了缩进

标签: c queue fifo


【解决方案1】:

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

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

    // body of afficher function    

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

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

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

【讨论】:

  • 谢谢,在affiche 中通过引用传递f 解决了它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-28
  • 2012-05-23
相关资源
最近更新 更多