【发布时间】: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 = &tail;您正在创建一个指向 local 变量的指针。函数结束后,此指针变为悬空,因此您的代码在尝试读取此指针时具有 未定义的行为 -
@UnholySheep 知道了,已经解决了,谢谢
标签: c pointers linked-list variadic