【问题标题】:How can I print the values in my linked list?如何打印链接列表中的值?
【发布时间】:2013-05-28 17:14:32
【问题描述】:

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

例如,当我将&head 传递给采用node **location 的函数时,我想检查location(因此head)内部的值是否为NULL,我应该使用@ 987654326@还是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(&current, i+1))
    { ++i; }

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

【问题讨论】:

    标签: c pointers struct linked-list pass-by-pointer


    【解决方案1】:

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

    您应该在 main 函数中使用 &amp;current-&gt;next 调用它。

    【讨论】:

    • 我需要了解为什么这是正确的位置,而且我的程序可能充满了错误,以至于无法注意到它是否修复了任何东西。我不知道如何调试这个问题。
    • @Leonardo 创建“头”节点时,将其分配给current。然后你用&amp;current 调用return_append_tail,然后函数用它分配的新节点覆盖 current 指针。如果您使用&amp;current-&gt;next 调用该函数,该函数会将新分配的节点放入current-&gt;next,从而将新节点附加到列表中。
    • @Leonardo 一种调试方法是在调试器中单步执行代码,您会希望注意到在return_append_tail 中location 变量的值永远不会改变,在其他情况下单词它总是指向同一个位置。您还会注意到 head-&gt;next 永远不会被设置。
    • 谢谢,我会为此努力找一个好的调试器并学习使用它,感谢您解释得很好。
    猜你喜欢
    • 2014-03-02
    • 2010-10-24
    • 2017-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    相关资源
    最近更新 更多