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;
}
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)
//^
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With