c++ - 如何使用 "new"分配函数内点引用参数的内存

标签 c++ memory reference point

这是我的代码

#include <stdio.h>
#include <stdlib.h>
struct ListNode {
 int val;
 ListNode *next;
 ListNode(int x) : val(x), next(NULL) {}
};

void insert(ListNode *&head,int value)
{
    ListNode *node;
    node = head;
    if(!node)
    {
        //node = new ListNode(value);
        head = new ListNode(value);
    }
    else
    {
        while(node->next != NULL)
            node = node->next;
        node->next = new ListNode(value);
    }
}
void print(ListNode *head)
{
    ListNode *node = head;
    for(;node!=NULL;){
        printf("%d ",node->val);
        node = node->next;
    }
}
int main(int argc,char *argv[])
{
    ListNode *head = NULL;
    insert(head,0);

    insert(head,1);
    insert(head,2);
    print(head);
    return 0;
}

在函数 insert 中,如果我将 head 传递给点 node,并使用 node = new ListNode(value); ,插入操作失败,head 仍然是 NULL。但是我使用 new 直接分配内存给head,它有效。我对C++中函数内部的点引用感到困惑,希望有人能帮我弄清楚。

最佳答案

这个:

ptr = new whatever;

分配内存,可能调用构造函数,并ptr 分配一个新值。

现在考虑这两个函数:

void foo1(int &n)
{
  int k=n;
  k=5;
}

void foo2(int &n)
{
  n=5;
}

在我调用foo1 之后,我(通过引用)传递的变量值没有改变。但是在我调用 foo2 之后,它是 5。

关于c++ - 如何使用 "new"分配函数内点引用参数的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26113301/

相关文章:

c++ - Qt - Qt 如何捕获未连接的点击事件(自动连接)?

memory - 如何在 N64 仿真器中构建内存映射?

c++ - 如何删除 vector 中的元素。 (删除无效)

visual-studio-2008 - 通过 NAnt 与 Visual Studio 构建 - 缺少一个 dll

C++98,但 clang-tidy 说使用 nullptr?

c++ - 如何为 COM 接口(interface)中的方法生成弃用警告 (c++)

performance - Hibernate 适合批处理吗?内存使用情况如何?

c++ - 为什么允许悬挂引用?

c++ - 由引用 : what am I doing wrong? 引起的意外复制构造

c++ - 如何知道哪个用户帐户运行特定的 Windows 服务?