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

how to use "new" to allocate memory of the point reference argument inside a function

本文关键字:引用 参数 内存 分配 何使用 new 函数      更新时间:2023-10-16

这是我的代码

#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传递到点节点,并使用节点=新ListNode(值) ,插入操作失败,head仍然为NULL。但我使用new直接将内存分配给,就可以工作了。我对C++中函数内部的点引用感到困惑,希望有人能帮我弄清楚。

这:

ptr = new whatever;

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

现在考虑这两个函数:

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

在我调用foo1之后,我(通过引用)传递的变量的值保持不变。但在我呼叫foo2之后,它是5。

找到我的内联注释,了解的每一步都在做什么

node = head; //! Here your node pointer pointing to the memory pointed by head
if(!node) //! You are checking if that memory is null or not
{
    node = new ListNode(value); //! now you are pointing your node pointer to some newly allocated memory, there is no impact on head pointer.
    //! If you want to change the head pointer also so
    head = node; //! Now head also pointing to the newly allocated location.
}