我一天中有很大一部分時間都在試圖用鏈表編寫一個簡單的程序。我的主要問題似乎並不理解爲什麼我訪問的內存不是我認爲的內存。我是瘋狂的printf,輸出所有可能的數據形式,但仍然無法理解爲什麼它不起作用。如何打印鏈接列表中的值?
例如,當我通過&head
到這需要node **location
函數,並且我要檢查內location
(因此head
)的值是否爲NULL
與否,我應該使用if(!*location) return;
或應該使用if(!location) return;
,看來以後是正確的,但爲什麼?
而當我想創建一個node *current
在函數內部跟蹤的東西,我應該先從node* current = *head
或node* current = head
,最重要的是,爲什麼?我注意到後者更好,但我仍然無法理解它。當我聲明陳述時,警告消失,但它似乎沒有解決任何問題。
以下是我一直在寫的一些函數,請給我一些暗示我在代碼中沒有意義的地方。最好,我希望理解爲什麼輸出似乎是一個內存位置,然後訪問錯誤的內存。
#include <stdio.h>
#include <stdlib.h>
typedef struct node_struct
{
int val;
struct node *next;
} node;
node* return_create_neck(node **head, int value)
{
node* ptr;
*head = ptr = (node *)malloc(sizeof(node));
(*head)->val = value;
(*head)->next = NULL;
return ptr;
}
node* return_append_tail(node **location, int value)
{
node* ptr;
*location = ptr = (node *)malloc(sizeof(node));
(*location)->val = value;
(*location)->next = NULL;
return ptr;
}
void print_linked_list(node **head)
{
if(!head)
return;
node *current = head;
while(current)
{
printf("%d ", current->val);
current = current->next;
}
printf("\n");
return;
}
int main(void)
{
node *head=NULL, *current=NULL;
int i=0;
for(current = return_create_neck(&head, 1);
i < 4;
current = return_append_tail(¤t, i+1))
{ ++i; }
printf("Pritning...\n");
print_linked_list(&head);
return 0;
}
但是我需要理解爲什麼這是正確的位置,然而我的程序可能太過於充滿了bug來注意它是否修復了任何東西。我無法知道如何調試此問題。 – Leonardo
@Leonardo創建「head」節點時,將其分配給「current」。然後你用'&current'調用'return_append_tail',然後該函數用它分配的新節點_overwrites_'current'指針。如果用'&current-> next'調用該函數,該函數會將新分配的節點放入'current-> next'中,從而將新節點附加到列表中。 –
@Leonardo調試這種方法的一種方法是逐步調試調試器中的代碼,並且希望注意到在'return_append_tail'中,'location'變量的值永遠不會改變,換句話說,它總是指向相同的位置。你也會注意到'head-> next'永遠不會被設置。 –