How to allocate the space without changing address in cpp?

Viewed 93

for example I have a struct now

struct TreeNode {
  int val;
  TreeNode *left;
  TreeNode *right;
  TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

I first have a pointer, but I do not allocate space for it, so just

TreeNode* p;

I want to allocate the space later, for example, in the other function, like below

void allo(TreeNode* p, int val){
  p = new TreeNode(val);
}
allo(p,5);
// I want to get the original p here

But this new method change the address of the original p, which I could not trace it anymore. So is there a method to allocate without changing the address? The limitation is that I want to separate the definition and the allocation, just like above, for example, define outside a function and allocate inside the function.

2 Answers

You need to pass the parameter by reference, if you want to manage this pointer outside this function. Otherwise a copy of the pointer is passed to the function allo. This copying changes the pointer.

Try like this (if I understand the essence of the question):

void allo(TreeNode*& ptr, int val)
{
    ptr = new TreeNode(val);
}

First of all:

You should NOT use raw owning pointers but smart pointers like std::unique_ptr<> or std::shared_ptr<> or RAII containers.

Your function allo() will do nothing to the pointer you pass to it because it takes the pointer by value (copy) and there is no way allo() could magically alter the adress of the pointer you pass it nor it's value. All that gets changed is the value of the parameter p which is local to your function, so the memory allocated effectively leaks.

Either, pass the paramter by reference so it can be altered within the function:

void allo(TreeNode* &ptr, int val)
{
    ptr = new TreeNode(val);
}

TreeNode *p{ nullptr };  // you shouldn't leave pointers uninitialized

// ...

allo(p, 42);

or return a value:

TreeNode* allo(int val)
{
    return new TreeNode(val);
}

// ...

TreeNode *p{ nullptr };

// ...

p = allo(42);

In both cases p points to the object allocated in allo() after the function call.

Related