Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing pointer of dynamic var by reference

Tags:

c++

pointers

I'm trying to create dynamic variable and pass its address by reference within new_test function, but it doesn't work. What am I doing wrong?

The code:

#include <iostream>
using namespace std;

struct test
{   
    int a;
    int b;
};  

void new_test(test *ptr, int a, int b)
{   
    ptr = new test;
    ptr -> a = a;
    ptr -> b = b;
    cout << "ptr:   " << ptr << endl; // here displays memory address
};  

int main()
{   

    test *test1 = NULL;

    new_test(test1, 2, 4); 

    cout << "test1: " << test1 << endl; // always 0 - why?
    delete test1;

    return 0;
}
like image 448
Silvia Torque Avatar asked Jan 13 '23 10:01

Silvia Torque


2 Answers

The code does not pass the pointer by reference so changes to the parameter ptr are local to the function and not visible to the caller. Change to:

void new_test (test*& ptr, int a, int b)
                  //^
like image 167
hmjd Avatar answered Jan 14 '23 22:01

hmjd


Here:

void new_test (test *ptr, int a, int b)
{   
    ptr = new test; //<< Here ptr itself is a local variable, and changing it does not affect the value outside the function
    //...

You are changing the pointer value itself, so you need a pointer to pointer, or a reference to a pointer:

Pointer of a pointer:

void new_test (test **ptr, int a, int b)
{   
    *ptr = new test;
    (*ptr) -> a = a;
    (*ptr) -> b = b;
    cout << "ptr:   " << *ptr << endl; // here displays memory address
}

and call using:

new_test (&test1, 2, 4);

Reference to a pointer:

void new_test (test *& ptr, int a, int b) {/.../ }

I don't recommend mixing pointer and reference, because it makes the program hard to read and track. But it is personal preference.

like image 29
SwiftMango Avatar answered Jan 15 '23 00:01

SwiftMango