【问题标题】:Print a linked list in C在 C 中打印一个链表
【发布时间】:2021-01-23 15:20:40
【问题描述】:

我正在为 Lisp 编译器开发一个链表 API,但我选择用 C 编写这部分,因为用汇编编写它不会很有趣。我可以使用下面的list 函数成功地从一系列元素中创建一个链表。我已经验证它可以工作,如下面的main 中的示例所示。但是为什么我的函数print_list 只打印第一个元素,然后是零?我感到很困惑。如果您了解出了什么问题,请提供任何帮助。

#include <stdio.h>
#include <stdarg.h>

typedef struct Node Node;
struct Node {
    int head; // make to a union later
    Node* tail;
};

//////////
Node cons(int curr, Node* next) {Node cell = {curr, next}; return cell;}
int car(Node node) {return node.head;}
Node* cdr(Node node) {return node.tail;}
//////////
void print_elems(Node node) {
    printf("%d", node.head);
    if (node.tail == NULL) return;
    printf(" ");
    print_elems(*node.tail);
}

void print_list(Node node) {
    printf("(");
    print_elems(node);
    printf(")\n");
}
//////////
Node make_pairs(va_list args, int argc) {
    Node linked_list;
    linked_list.head = va_arg(args, int);
    if (argc == 0) {
        linked_list.tail = NULL;
        return linked_list;
    }
    Node tail = make_pairs(args, argc - 1);
    linked_list.tail = &tail;
    return linked_list;
}

Node list(int length, ...) {
    va_list elems;
    va_start(elems, length);
    Node linked_list = make_pairs(elems, length);
    va_end(elems);
    return linked_list;
}
//////////

int main() {
    Node big_list = list(5, 1, 2, 3, 4, 5);

    /*
    This is NULL, as expected:
    big_list.tail -> tail -> tail -> tail -> tail -> head

    And this is 1:
    big_list.head
    */

    // but why does this only print "(1 0)"?
    print_list(big_list);
}

【问题讨论】:

  • linked_list.tail = &amp;tail; 您正在创建一个指向 local 变量的指针。函数结束后,此指针变为悬空,因此您的代码在尝试读取此指针时具有 未定义的行为
  • @UnholySheep 知道了,已经解决了,谢谢

标签: c pointers linked-list variadic


【解决方案1】:

你可以用这种方式打印链表:这是一个例子; 我的目标只是让您注意到指针没有局部变量问题

typedef struct Node Node;
Node* first_element = create_list; // just for understanding "first element" is the linked list
Node* ptr = first_element; // copy in another pointer your list then you will avoid loosing your first element and breaking your list (personnal advice : not needed)

while  (ptr->tail){
    ptrinf("%d\n", ptr->head); // for exemple
    ptr = ptr->tail;
} 

//after the while ptr = the last element because ptr->tail == NULL

格式化为它看起来像这样:

#include <stdio.h>
typedef struct Node Node;

void display_list (Node* first_element)
{
        Node* ptr = first_element; // copy in another pointer your list then you will avoid loosing your first element and breaking your list (personnal advice : not needed)

        while  (ptr->tail){
            ptrinf("%d\n", ptr->head); // for exemple
            ptr = ptr->tail;
        }

        //after the while ptr = the last element because ptr->tail == NULL
}

如果我没有很好地回答问题,请告诉我,我是新人,我会改进^^。

希望对你有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-23
    相关资源
    最近更新 更多