0

在一天的大部分时间里,我一直在尝试用链表编写一个简单的程序。我的主要问题似乎是不明白为什么我正在访问的内存不是我想的那样。我对 printf 很疯狂,我可以输出所有可能形式的数据,但仍然无法理解为什么它不起作用。

例如,当我将 传递&head给一个函数时,node **location我想检查内部location(因此head)的值是否是NULL,我应该使用if(!*location) return;还是应该使用if(!location) return;,看起来后者是正确的,但为什么呢?

当我想创建一个node *current内部函数来跟踪事物时,我应该从node* current = *heador开始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(&current, i+1))
    { ++i; }

    printf("Pritning...\n");
    print_linked_list(&head);
    return 0;
}
4

1 回答 1

2

您的return_append_tail函数实际上不会附加任何内容,除非使用正确的 调用location,而您没有这样做。

您应该&current->nextmain函数中调用它。

于 2013-06-02T10:12:36.723 回答