1

所以我对 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”。它给出了命令行上最后一个参数的无限循环(“./test 一二三”给出“我有三。”一遍又一遍地忽略“一”和“二”,但前面的几行是相同的)。

我认为这与动态函数中的不良指针管理有关,但我无法弄清楚为什么它将自己设置为自己的“下一个”节点。

4

2 回答 2

2

The problem is here:

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

By allocating next like this, it remains tied to the stack and doesn't actually change address on each iteration. It should be a new object each time:

for (i = 0; i < argc; i++) {
    node *next = malloc (sizeof node);
    next->word = argv[i];
    next->next = NULL;
    cur->next = next;
    cur = next;
}

Also, node_new() can't be used because it doesn't allocate any lasting new memory either.

于 2013-06-25T17:29:43.287 回答
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

于 2013-06-25T17:31:22.150 回答