不带malloc的链表

问题描述 投票:0回答:1

我自己开始学习C,根据《Programming in C (4th Edition)》这本书,作者定义了一个链表如下:

struct entry
{
    int value;
    struct entry *next;
};

struct entry *createNewLinkList(void)
{
    struct entry n1, n2, n3;
    struct entry *list_pointer = &n1;

    n1.value = 100;
    n1.next = &n2;
    n2.value = 200;
    n2.next = &n3;
    n3.value = 300;
    n3.next = NULL;
    return list_pointer;
}

void print_linked_list(struct entry *linked_list)
{
    struct entry *current = linked_list;
    while (current != NULL)
    {
        printf("%d\n", current->value);
        current = current->next;
    }
    printf("\n");
}

int main(void)
{
    struct entry *linked_list = createNewLinkList(); //DEBUG: This line is fine linked_list: {value:100, next:0x000000016fdff200}
    printf("Original list \n");
    print_linked_list(linked_list);   //DEBUG: it is wrong after entering this line linked_list:{value:1876947504, next:0x8b7a000100003f48}
}

我不明白为什么

linked_list
的值就变成了某个地址。

如果我像这样使用 malloc 创建链表,它将起作用:

struct entry *createNewLinkList(void)
{
    struct entry *n1 = (struct entry *)malloc(sizeof(struct entry));
    struct entry *n2 = (struct entry *)malloc(sizeof(struct entry));
    struct entry *n3 = (struct entry *)malloc(sizeof(struct entry));

    n1->value = 100;
    n1->next = n2;

    n2->value = 200;
    n2->next = n3;

    n3->value = 300;
    n3->next = NULL;
    return n1;
}

提前谢谢您,

c pointers malloc
1个回答
0
投票

书中的程序有未定义的行为。

函数

createNewLinkList
返回一个指向局部对象(
n1
)的指针,该对象在退出函数后将不存在(以及通过指针链接的其他局部变量)

struct entry *createNewLinkList(void)
{
    struct entry n1, n2, n3;
    struct entry *list_pointer = &n1;

    n1.value = 100;
    n1.next = &n2;
    n2.value = 200;
    n2.next = &n3;
    n3.value = 300;
    n3.next = NULL;
    return list_pointer;
}

所以在函数中引用指针

print_linked_list

void print_linked_list(struct entry *linked_list)
{
    struct entry *current = linked_list;
    while (current != NULL)
    {
        printf("%d\n", current->value);
        current = current->next;
    }
    printf("\n");
}

调用未定义的行为。

© www.soinside.com 2019 - 2024. All rights reserved.