通过引用传递动态var的指针 [英] Passing pointer of dynamic var by reference
本文介绍了通过引用传递动态var的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图创建动态变量并通过引用在 new_test
函数中传递它的地址,但它不工作。
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; //这里显示内存地址
};
int main()
{
测试* test1 = NULL;
new_test(test1,2,4);
cout<< test1:<< test1<< endl; // always 0 - why?
delete test1;
return 0;
}
解决方案
代码不通过指针,因此对参数 ptr
的更改对于函数是本地的,对调用者不可见。更改为:
void new_test(test *& ptr,int a,int b)
// ^ b $ b
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)
//^
这篇关于通过引用传递动态var的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文