我一天中有很大一部分时间都在试图用链表编写一个简单的程序。我的主要问题似乎并不理解为什么我访问的内存不是我认为的内存。我是疯狂的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'永远不会被设置。 –