C链表循环引用

时间:2013-06-25 17:23:35

标签: c linked-list circular-reference

所以我对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;
}

如果我只是在没有参数的情况下运行它(&#34; ./ test&#34;),则输出为:

PREDEFINED:
I have ROOT.
I have A.
I have B.
I have C.
Done.
DYNAMIC:
I have ROOT.
I have ./test.
Done.

但如果我提出任何论据,而不是&#34;我有./test."它给出了无限循环,无论命令行上的最后一个参数是什么(&#34; ./测试一两三&#34;给出&#34;我有三个。&#34;一遍又一遍地忽略&#34 ;一个&#34;和&#34;两个&#34;,但前面的行是相同的。)

我认为它与动态函数中的错误指针管理有关,但我无法弄清楚为什么它将自己设置为自己的&#34; next&#34;节点

2 个答案:

答案 0 :(得分:2)

问题在于:

for (i = 0; i < argc; i++) {
    node next = node_new(argv[i]);
    cur->next = &next;
    cur = &next;
}

通过像这样分配next,它仍然与堆栈绑定,并且实际上不会在每次迭代时更改地址。每次都应该是一个新对象:

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()无法使用,因为它也没有分配任何持久的新内存。

答案 1 :(得分:2)

问题出在你的for循环中。每次迭代都使用堆栈上的相同内存位置来存储next变量。因此,有效地,&next给出的内存位置是整个for循环的常量,当您运行traverse时,该内存位置包含next的最后一个值}。

您的for循环等同于此版本,这可能会带来更多亮点:

int i;
node next;  // note this line
for (i = 0; i < argc; i++) {
    next = node_new(argv[i]);
    cur->next = &next;
    cur = &next;
}

如果您希望能够传递其地址,或者将其地址存储在其他数据结构中,则需要在堆上创建新节点。阅读mallocfree