簡體   English   中英

打印鏈接列表時出現的問題

[英]Issue when printing Linked List

我正在嘗試創建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;
}

問題是,在new_msg()函數中,您定義了一個本地變量m ,該變量從不存儲 ,並且全局queue也從不更新。 在每個調用中, queue等於NULL。

接下來,在您的printList()函數中,

  1. temp是單位化的
  2. while (temp->next != NULL)可能在第一次迭代中評估為false。

這兩個函數都是無效的,並且具有未定義的行為,至少是因為在這兩個函數中都嘗試寫入未分配的內存或從中讀取。

嘗試以下

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 )

假設new_msg是正確的, new_msg指針列表打印為new_msg ,這可能會導致核心轉儲。

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

M temp = queue;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM