如何使用"new"在函数内分配点引用参数的内存
how to use "new" to allocate memory of the point reference argument inside a function
这是我的代码
#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.
}
相关文章:
- 将const引用参数初始化为默认参数会导致悬空引用吗
- 具有常量引用参数的函数模板专用化
- C++:常量引用参数
- 字符串引用参数的效率C++
- 通过非常量引用参数修改常量引用参数
- 如何将指针变量作为引用参数传递?
- C++初始化 std::function 时如何将占位符绑定到引用/引用参数?
- 移动类的成员作为常量引用参数传递
- C++带有适用于左值和右值的引用参数的函数
- constexpr 函数的常量引用参数:gcc/msvc vs clang/icc
- 如何使用类型特征将函数的通用引用参数限制为 r 值引用?
- 委托构造函数和引用参数
- 对 const 引用参数使用默认值会导致崩溃
- 为什么我们不允许将纯引用参数传递给 std::thread,但允许传递原始指针?
- 为什么我需要将默认引用参数定义为 const 以便为其分配一个左值?
- 将非左值作为常量引用参数传递.临时是在本地作用域还是在调用方作用域中创建的?
- 如何强制函数仅接受左值引用参数
- 模板引用参数推断失败C++
- 非类型引用参数可以在运行时修改,这是否意味着模板可以在运行时实例化?
- 将unique_ptr作为引用参数或常量传递unique_ptr引用