【问题标题】:Can't printf contents of a single-linked-list of strings无法打印字符串单链表的内容
【发布时间】:2011-06-05 10:35:15
【问题描述】:

我在这里写了这段代码,我已经将它与其他几个函数和一个 main 链接好了,它工作没有问题并且编译时没有警告(我正在使用 gcc 编译器)。

我使用一个指针数组 (archive.products[]) 作为多个字符串列表的入口点。我还在开始,所以每个列表只有一个节点。

我遇到的问题是我无法让函数 lprintf 在屏幕上显示我创建的单节点字符串列表的组件。请注意,位于 push 函数内的 printf 打印正常。所以我知道 push 正在做它的工作......

如果有人知道我可能做错了什么,请在下面回复。 提前谢谢你!

#define line_length 61
#define max_products 10

struct terminal_list {
  char terminal[line_length];
  struct terminal_list *next;
}*newnode, *browser;
typedef struct terminal_list tlst;

struct hilevel_data {
 char category[line_length];
 tlst *products[max_products];
};
typedef struct hilevel_data hld;

void import_terms(FILE *fp, hld archive){
  char buffer[line_length];
  char filter_t[3] = "}\n";
  int i = 0, j = 0;

  while (!feof(fp)) {    
    fgets(buffer, line_length, fp);
    if (strcmp(buffer, filter_t) == 0) {
      return;
    }

    head_initiator(archive, i);
    push(buffer,archive, i);

    lprintf();

    i++;
  }
}

void head_initiator(hld archive, int i){
  browser = NULL;
  archive.products[i] = NULL;
}

void push(char buffer[],hld archive, int i){
 newnode = (tlst *)malloc(sizeof(tlst));
 strcpy(newnode->terminal, buffer);
//  printf("%s", newnode->terminal);
 archive.products[i] = browser;
 newnode->next = browser;
 browser = newnode;
}

void lprintf(){
  tlst *p;
  p = browser;
  if (p = NULL){
    printf("empty\n");    
  }
  while(p!=NULL){
    printf("%s\n", p->terminal);
    p=p->next;
  }
}

【问题讨论】:

    标签: c string list function


    【解决方案1】:
    if (p = NULL){
        printf("empty\n");    
    }
    

    我想你是说

    if (p == NULL){
        printf("empty\n");    
    }
    

    您实际上是在使用 p = NULL 清空列表。

    【讨论】:

      【解决方案2】:

      开启:void lprintf()

      if (p = NULL)
      

      应该是

      if (p == NULL)
      

      【讨论】:

      • 如果你一开始就写得更清楚if (!p),就永远不会有问题......
      猜你喜欢
      • 2021-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多