在一天的大部分时间里,我一直在尝试用链表编写一个简单的程序。我的主要问题似乎是不明白为什么我正在访问的内存不是我想的那样。我对 printf 很疯狂,我可以输出所有可能形式的数据,但仍然无法理解为什么它不起作用。
例如,当我将 传递&head
给一个函数时,node **location
我想检查内部location
(因此head
)的值是否是NULL
,我应该使用if(!*location) return;
还是应该使用if(!location) return;
,看起来后者是正确的,但为什么呢?
当我想创建一个node *current
内部函数来跟踪事物时,我应该从node* current = *head
or开始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;
}