c - 传递给函数的指针没有更新

标签 c

<分区>

我是 C 的新手。

我正在编写简单的链表应用程序。

这是我的代码:

typedef struct
{
    struct node * NextNode;
    int data;
}node;

void addNode(int data, node * Head)
{
    if (Head == NULL)
    {
        Head = malloc(sizeof(node));
        Head->data = data;
        Head->NextNode = NULL;
        return;
    }
    node* CurrentNode = Head;
    node* _Newnode = malloc(sizeof(node));
    (*_Newnode).data = data;
    _Newnode->NextNode = NULL;
    while (CurrentNode->NextNode != NULL)
    {
        CurrentNode = CurrentNode->NextNode;
    }
    CurrentNode->NextNode = _Newnode; 
}

问题出现在传递 Head = NULL 时 通过 head= NULL 后,Head 没有改变并保持为 NULL

我做错了什么? 您能否也解释一下下面发生的事情?
谢谢

最佳答案

指针是按值传递的——如果你更新它,你所做的就是更新它的本地副本。如果你想更新指针,你应该传递指向它的指针,并更新它的解引用:

void addNode(int data, node ** Head)
{
    if (*Head == NULL)
    {
        *Head = malloc(sizeof(node));
        *Head->data = data;
        *Head->NextNode = NULL;
        return;
    }
    node* CurrentNode = *Head;
    node* _Newnode = malloc(sizeof(node));
    (*_Newnode).data = data;
    _Newnode->NextNode = NULL;
    while (CurrentNode->NextNode != NULL)
    {
        CurrentNode = CurrentNode->NextNode;
    }
    CurrentNode->NextNode = _Newnode; 
}

关于c - 传递给函数的指针没有更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26368181/

相关文章:

c - 如何查找 B 树的层数

c - 1 左移 n

c - Linux内核函数和内核模块开发

c - c 中 4x4 矩阵的 getter 问题

c - PCI_VDEVICE 和 PCI_DEVICE 有什么区别?

c - 全局变量的位置 w/o -fPIC

c++ - 使用 WaveOutOpen(C++) 播放 .wav

c - 如何从 NSURL 获取结构文件?

c - 有没有跨平台的小型\可移植C图像编辑库?

C 代码到 HEX 文件