C++ 通过引用传递动态变量的指针
我试图在C++ 通过引用传递动态变量的指针,c++,pointers,C++,Pointers,我试图在new\u 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;
new\u 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;
}
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
}
void new_test (test *& ptr, int a, int b) {/.../ }
#包括
使用名称空间std;
结构测试
{
INTA;
int b;
};
无效新测试(测试*ptr,内部a,内部b)
{
ptr=新试验;
ptr->a=a;
ptr->b=b;
cout代码不通过引用传递指针,因此对参数ptr
的更改是函数的本地更改,调用方不可见。更改为:
void new_test (test*& ptr, int a, int b)
//^
在这里:
对指针的引用:
#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;
}
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
}
void new_test (test *& ptr, int a, int b) {/.../ }
我不建议混合指针和引用,因为这会使程序难以阅读和跟踪。但这是个人偏好。@Davlog,是的,但需要在函数定义中取消引用。所有这些指针问题都不好(请习惯RAII)-1