通过引用传递动态var的指针

Sil*_*que 4 c++ pointers

我正在尝试创建动态变量并在new_test函数内通过引用传递其地址,但它不起作用.我究竟做错了什么?

代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

hmj*_*mjd 8

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)
                  //^
Run Code Online (Sandbox Code Playgroud)