who*_*ows 5 c++ struct pointers
我正在尝试将结构指针传递给函数并通过指针初始化结构.知道为什么这不起作用吗?
struct Re
{
int length;
int width;
};
void test (Re*);
int main()
{
Re* blah = NULL;
test(blah);
cout << blah->width;
return 0;
}
void test(Re *t) {
t = new Re{5, 5};
}
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
xor*_*guy 12
指针被复制到函数中,因为它是通过值传递的.您必须将指针传递给指针或指针的引用才能初始化它:
void test(Re *&t) {
t = new Re{5, 5};
}
Run Code Online (Sandbox Code Playgroud)