所以我是 C 的新手,但不是编程的新手。我正在尝试学习 C,所以我决定尝试实现一个简单的链表。
代码如下:
#include <stdio.h>
typedef struct node node;
struct node {
char *word;
node *next;
};
// Returns a node.
node node_new(char *word) {
node n;
n.word = word;
n.next = NULL;
return n;
}
// Traverses the linked list, spitting out the
// words onto the console.
void traverse(node *head) {
node *cur = head;
while (cur != NULL) {
printf("I have %s.\n", cur->word);
cur = cur->next;
}
printf("Done.\n");
return;
}
// In here I get circular references whenever I pass a second argument.
void dynamic(int argc, char **argv) {
printf("DYNAMIC:\n");
node n = node_new("ROOT");
node *cur = &n;
int i;
for (i = 0; i < argc; i++) {
node next = node_new(argv[i]);
cur->next = &next;
cur = &next;
}
traverse(&n);
}
void predefined(void) {
printf("PREDEFINED:\n");
node n = node_new("ROOT");
node a = node_new("A");
node b = node_new("B");
node c = node_new("C");
n.next = &a;
a.next = &b;
b.next = &c;
traverse(&n);
}
int main(int argc, char **argv) {
predefined();
dynamic(argc, argv);
return 0;
}
如果我只是不带参数运行它 ("./test"),输出是:
PREDEFINED:
I have ROOT.
I have A.
I have B.
I have C.
Done.
DYNAMIC:
I have ROOT.
I have ./test.
Done.
但是如果我提出任何论点,而不是“我有./test”。它给出了一个无限循环,无论命令行上的最后一个参数是什么(“。/测试一二三”给出“我有三个。”一遍又一遍地忽略“一”和“二”,但前面的几行是相同)。
我认为这与动态函数中糟糕的指针管理有关,但我不明白为什么它将自己设置为自己的“下一个”节点。
最佳答案
问题出在这里:
for (i = 0; i < argc; i++) {
node next = node_new(argv[i]);
cur->next = &next;
cur = &next;
}
通过像这样分配 next
,它仍然绑定(bind)到堆栈并且实际上不会在每次迭代时更改地址。每次都应该是一个新对象:
for (i = 0; i < argc; i++) {
node *next = malloc (sizeof node);
next->word = argv[i];
next->next = NULL;
cur->next = next;
cur = next;
}
此外,node_new()
也不能使用,因为它也没有分配任何持久的新内存。
关于C链表循环引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17303648/