从insert_beg函数出来时,分配给指针的内存不会保留并丢失

问题描述

一旦我们离开函数insert_beg,分配给头指针的内存就会丢失,并且头指针再次变为NULL。尽管我传递了指针,为什么仍会出现这种现象?请指导我如何保留由malloc()分配的内存块。

#include <stdlib.h>

struct node
{
    int data;
    struct node *next;
};

void insert_beg(struct node *head,int data)
{
    if(head==NULL)
    {
        struct node *tmp_node;
        tmp_node = (struct node*)malloc(sizeof(struct node));
        tmp_node->data = data;
        tmp_node->next = NULL;
        head = tmp_node;
    }

    else
    {
        struct node *tmp_node;
        tmp_node = (struct node*)malloc(sizeof(struct node));
        tmp_node->data = data;
        tmp_node->next = head;
        head = tmp_node;
    }
}


void display(struct node *head)
{
    if(head==NULL)
    {
        printf("UNDERFLOW");
    }

    else
    {
        struct node *tmp = head;

        while(tmp!=NULL)
        {
            printf("%d ",tmp->data);
            tmp = tmp->next;
        }
    }
    
}

int main()
{
    struct node *head = NULL;
    insert_beg(head,12);
    display(head);
 
} ```

Expected output: 12
Observed output: UNDERFLOW

解决方法

函数setInterval(() => { // do something every 5 seconds },5000); 处理传递给它的指向头节点的指针的值的副本。参数insert_beg是函数的局部变量,该函数获取指向头节点的原始指针的值的副本。因此,局部变量的更改不会影响用作参数的原始指针

您应该通过引用将指针传递到头节点。

在C中,按引用传递是指通过对象的指针间接传递对象。

可以通过以下方式声明和定义函数。

struct node *head

该函数可以像

那样调用
int insert_beg( struct node **head,int data )
{
    struct node *tmp_node = malloc( sizeof( struct node ) );
    int success = tmp_node != NULL;

   
    if ( success )
    {
        tmp_node->data = data;
        tmp_node->next = *head;
        *head = tmp_node;
    }

    return success;
}

或喜欢

insert_beg( &head,12 );