簡體   English   中英

C中鏈表的邏輯錯誤

[英]Logical error for linked list in C

#include <stdio.h>
#include <stdlib.h>
#define UINT unsigned int

struct item
{
UINT   time ;           // time in tics which is used to order the list.
UINT   id ;             // penguin id number.
UINT   event ;          // event this item describes.
struct item  *next ;    // pointer to next item in list.
};

struct item *head=NULL;
struct item *trail=NULL;


void link_list(UINT time, UINT id, UINT event)
{
struct item *t=NULL;
static int i=0;
if(i==0)
{
    head->time=time;
    head->id=id;
    head->event=event;
    trail=head;
    trail->next=NULL;
    i++;
    printf("Hello Word\n");
}
t=malloc(sizeof(struct item));
trail->next=t;
trail->time=time;
trail->id=id;
trail->event=event;
trail=t;
trail->next=NULL;
if(i!=0)
    printf("I am \n");

}

int main(int argc, char *argv[])
{
UINT x[3]={4,5,7}, y[3]={40,50,60}, z[3]={100,900,500};
int i=0;
head=malloc(sizeof(struct item));

trail=head;
link_list(x[0], y[0], z[0]);
link_list(x[1], y[1], z[1]);
link_list(x[2], y[2], z[2]);


struct item *f=NULL;
f=head;
do
{
    printf("trail: %d %d %d\n", f->time, f->id, f->event);
    f=f->next;
}
while(f!=NULL);

return 0;
}  

美好的一天,

我目前在邏輯上對鏈接列表的代碼實現存在邏輯問題。 這段代碼是我用來將它集成到一個更大的程序中的框架,它將使用鏈表,所以我需要正確。

基本上發生的事情就是當我最終到達do while循環時,我將其用作調試行來查看鏈表的內容,我將在命令行中獲得此輸出:

小道:4 40 100

小道:5 50 900

小道:7 60 500

trail:0 0 0

我期待輸出是這樣的:

小道:4 40 100

小道:5 50 900

小道:7 60 500

我已經在我的代碼中排除了其他printf,因為它們只是用於檢查我是否確實正確地執行了我的功能。 這也許是無關的,但在linux下是否有更好的c調試器? 因為內置調試器在進入malloc命令時會發瘋,所以我必須調試我腦子里的所有程序。 :(

如果內置調試器是指gdb,你可以告訴它跳過malloc(); 但是,如果您的程序在malloc中崩潰,則會遇到內存分配或在程序中使用錯誤。

一個明顯的錯誤是你沒有在link_list()中正確初始化“t”,特別是t-> next就是垃圾,你的程序在嘗試跟隨它時可能會崩潰。 我認為你的意思是設置t-> time,t-> id等,而不是trail-> time。

附加到鏈表的最佳方法通常是有一個單獨的函數返回一個新的列表項,其中所有字段都已初始化,然后在例程中追加,只需操作指針即可。 如果您的列表頭只是一個指針而不是結構,它也會有所幫助,但這是一個樣式問題。

最重要的是使用一個為您提供鏈接列表的庫,但如果您正在了解鏈接列表,那就沒有用了!

您將新節點附加到尾部,然后將您的數據寫入尾節點,然后將尾指針移動到新節點:

t=malloc(sizeof(struct item));
trail->next=t;
trail->time=time;
trail->id=id;
trail->event=event;
trail=t;
trail->next=NULL;

t設置為新節點。 當前列表尾部的下一個指針被設置為指向t寫入由tail指向的節點的時間,id和事件字段。 尾部引用現在移動到t,它仍然不包含任何數據。

有很多東西可以改進這個代碼,從使用模塊化設計開始“列表”管理開始,但這是你的直接問題。

暫無
暫無

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

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