首页 > 解决方案 > 将节点附加到指针数组

问题描述

我目前正在学习使用 C 的数据结构,现在分配使用指针创建列表。然后我在尝试将元素添加到我创建的列表中时遇到了问题。这是我现在的代码。

#include <stdio.h>
#include <stdlib.h>

struct NODE
{
    int x;
    char c;
    struct NODE *next;
};
void make_list(struct NODE **n)
{
    for(int k = 0; k < 20; k++)
    {
        *n = (struct NODE *)malloc(sizeof(struct NODE));
        (*n)->x = k+1;
        (*n)->c = 'A'+k;
        n = &(*n)->next;
    }
    *n = NULL;
}

void print_list(struct NODE *node)
{
    int k = 0;
    printf("###### Content of list ######\n");

    while(node != NULL)
    {
        printf("[%d]:x = %d, c = %c\n", k++, node->x, node->c);
        node = node->next;
    }
}

void append_last_node(struct NODE *node)
{
    struct NODE *next;

    while(node->next != NULL)
    {
        node->next = next;
    }

    node->next = (struct NODE *)malloc(sizeof(struct NODE));

    node->next->next = NULL;
    node->next->x = 100;
    node->next->c = 'a';
}

int main()
{
    struct NODE *n;

    make_list(&n);
    print_list(n);

    append_last_node(n);
    print_list(n);

    return 0;

一旦我运行这个,只有我在 make_list 函数中创建的列表被打印,而 append_last_node 函数没有被打印,并且在我的列表打印后执行过程不会自动结束。

###### Content of list ###### 
[0]:x = 1, c = A 
[1]:x = 2, c = B 
[2]:x = 3, c = C 
[3]:x = 4, c = D 
[4]:x = 5, c = E 
[5]:x = 6, c = F 
[6]:x = 7, c = G 
[7]:x = 8, c = H 
[8]:x = 9, c = I 
[9]:x = 10, c = J 
[10]:x = 11, c = K 
[11]:x = 12, c = L 
[12]:x = 13, c = M 
[13]:x = 14, c = N
[14]:x = 15, c = O 
[15]:x = 16, c = P 
[16]:x = 17, c = Q 
[17]:x = 18, c = R 
[18]:x = 19, c = S 
[19]:x = 20, c = T

我的 append_last_node 函数中是否有任何错误,或者我在那里遗漏了什么?

P/S:对不起我的英语不好。

标签: clistnodes

解决方案


让我们分析一下这段代码:

struct NODE *next;

while(node->next != NULL)
{
    node->next = next;
}

NODE首先声明一个指向的指针next,并且从不初始化。它指向内存的随机位置。一般来说,最好初始化一切。

node,作为参数传递,是列表的头部。

在第一次迭代中,node->next是列表的第二个元素,显然不是 null,因为列表应该有 20 个元素。

对于这个元素,你做 assign next,它是未初始化的。

接下来是未定义的行为。

此时node->next是一些随机地址,您的进程甚至可能无法访问。最后一个节点将附加到此随机内存位置或崩溃。

你所追求的是循环到列表的最后一个元素。所以:

struct NODE *curr = node;

while(curr->next != NULL)
{
    curr= curr->next;
}

curr最后一个节点也是如此。


推荐阅读