user3219735
user3219735

Reputation: 53

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

Here is my code

#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;
}

Inside function insert,if I pass head to the point node,and use node = new ListNode(value);,the insert action fail and head is still NULL.But I use new allocate memory to head directly,it works.I am confused about the point reference inside function in C++ and hope somebody help me figure it out.

Upvotes: 0

Views: 122

Answers (2)

Hemant Gangwar
Hemant Gangwar

Reputation: 2272

Find my inline comments to understand what each step is doing

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.
}

Upvotes: 1

Beta
Beta

Reputation: 99094

This:

ptr = new whatever;

allocates memory, maybe calls a constructor, and assigns a new value to ptr.

Now consider these two functions:

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

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

After I call foo1, the value of the variable I passed (by reference) is unchanged. But after I call foo2, it is 5.

Upvotes: 2

Related Questions