【问题标题】:Issue when printing Linked List打印链接列表时的问题
【发布时间】:2015-11-24 15:33:06
【问题描述】:

我正在尝试创建一个包含 5 个节点的链接列表并打印它们。我不知道为什么在打印链接列表时看不到结果,即使我没有收到错误并且我确信我的结构很好。我只看到空白屏幕。这是我的代码:

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


typedef struct msg *M;
struct msg{
    double id;
    M next;
};
M queue;

void new_msg(double id);
void printList();

void main()
{
    double r;

    srand(0);
    for(int i=0;i<5;i++){
        r = rand() % 100;
        new_msg(r);
    }

    printList(); // PRINT DOES NOT SHOW RESULTS :(
}

void printList()
{
    M temp;

    while (temp->next != NULL){
        temp = temp->next;

        printf("MSG ID:%6.3f \n", temp->id);
    } 
}

void new_msg(double id)
{
    M m;
    if(queue == NULL)
    {
        m = malloc(sizeof(struct msg));
    }
    else
    {
        m= queue;
        queue = queue->next; 
    }

    m->id = id;
    m->next = NULL;
}

【问题讨论】:

  • void main() --> int main(void)
  • 哦,对了。谢谢你。但仍然没有显示结果:(
  • 什么?那是评论,不是回答朋友!!
  • 您应该尝试使用调试器。单步执行代码时会出现几个错误。
  • 将指针隐藏在 typedef 后面的形式很糟糕。不要这样做。它让每个人都感到困惑,甚至可能是你。

标签: c linked-list printf singly-linked-list


【解决方案1】:

这两个函数都是无效的并且具有未定义的行为,至少因为在这两个函数中都试图写入或读取未分配的内存。

试试下面的

void printList()
{
    for ( M temp = queue; temp != NULL; temp = temp->next; )
    {
        printf("MSG ID:%6.3f \n", temp->id);
    } 
}


void new_msg(double id)
{
    M m = malloc( sizeof( struct msg ) );

    if ( m != NULL)
    {
        m->id = id;
        m->next = queue;
        queue = m; 
    }
}

请注意,尽管一些编译器允许使用返回类型为 void 的主声明,但这样的声明不符合 C 标准。

你应该写

int main( void )

【讨论】:

    【解决方案2】:

    问题是,在new_msg() 函数中,您定义了一个局部变量m,它永远不会存储,而全局queue 永远不会更新。在每次调用中,queue 都等于 NULL。

    接下来,在您的 printList() 函数中,

    1. temp 未初始化
    2. while (temp-&gt;next != NULL) 在第一次迭代中可能会评估为 false。

    【讨论】:

      【解决方案3】:

      假设new_msg 是正确的,您正在打印一个指向虚无的指针列表,这可能会导致核心转储。

      您的M temp; 未初始化。你可能想要:

      M temp = queue;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-21
        • 1970-01-01
        • 1970-01-01
        • 2022-06-15
        • 2017-08-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多