c - 通过函数传递时指向 NULL 的全局链表

标签 c pointers linked-list

我面临这个问题,如果我通过一个函数(插入一个节点)传递一个链表(我定义为全局),一旦指针返回到主函数,我总是得到一个 NULL 值。 但是,如果我将节点添加到全局定义中,它工作正常,这也是预期的。有人可以帮我解释一下为什么这段代码不起作用并且 *list 总是指向 NULL

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

    typedef struct node node;
    static node *list=NULL;

boolean add_node(node *list, int n, int val)
{

    node *temp=NULL;
    temp = (node *)malloc(sizeof(node));
    temp->val = val;
    temp->next = NULL;

    if((list==NULL) && (n!=0))
    {
        printf("link list is NULL and addition at non zero index !");
        return (FALSE);
    }

    if(list==NULL)
    {
       printf("list is NULL ");
       list= temp;
    }
    else if(n==0)
    {
       temp-> next = list;
       list=temp;
    }
    else
    {
        node *temp2;
        temp2 = list;
        int count =0;
        while(count++ != (n-1))
        {
          temp2 = temp2->next;
          if(temp2==NULL)
          {
            printf("nth index %d is more then the length of link list %d ",n,count);
            return (FALSE);
          }
        }

        node *temp3;
        temp3 = temp2->next;
        temp2-> next = temp;
        temp->next = temp3;
    }

    printf("List after node insertion \n");
    print_link_list(list);
    return (TRUE);
}

main()
{
     c= getchar();
     switch(c)
        {
            case 'I':
            {
                printf("Insert a index and value  \n");
                int index,value;
                scanf_s("%d",&index);
                scanf_s("%d",&value);
                if(add_node(list,index,value)==FALSE)
                {
                    printf("Couldn't add the node \n");
                }

                if(list==NULL)
                {
                    printf("\n After Insert op.,list is NULL, add %x",list);
                }
                else
                {
                    printf("After Inset op., list is not Null, add %x",list);
                }
            }
            break;
            case 'D':

....
}

最佳答案

全局变量list永远不会被修改,只有参数list

您可能希望该参数是指向指针的指针,并通过而不是 分配参数。

关于c - 通过函数传递时指向 NULL 的全局链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19501821/

相关文章:

c++ - Qt 如何管理从函数 QItemDelegate::createEditor() 返回的 Widget 指针的内存

python - 在Python中反转链表

c - y -= m < 3 是什么意思?

c - ACSL - 无法证明功能

c - 测试迭代指针之间的关系是否安全?

C:不兼容的指针类型初始化

java - 如何从文件中读取内容并将内容保存到链表中?

java - 有人可以告诉我我做错了什么吗?通过 LinkedList 进行计数和循环

C 从特定字符打印字符串

c - 如何同时应用多个过滤器?