gpt4 book ai didi

c++ - 双指针 vs 通过引用指针传递

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:43:18 25 4
gpt4 key购买 nike

<分区>

虽然理解了双指针的概念和应该在哪里使用它,但我有一个疑问。我试验了这段代码,发现我也可以使用通过引用传递指针而不是双指针。

#include<iostream>
using namespace std;
void modify_by_value(int* );
void modify_by_refrence(int* &);
int a=4, b=5;
void main()
{

int *ptr = NULL;
ptr = &a;
cout << "*ptr before modifying by value: " << *ptr << endl;
modify_by_value(ptr);
cout << "*ptr after modifying by value: " << *ptr << endl;
cout << "*ptr before modifying by refrence: " << *ptr << endl;
modify_by_refrence(ptr);
cout << "*ptr after modifying by refrence: " << *ptr << endl;

}
void modify_by_value(int* ptr) //this function can change *ptr but not the ptr(address contained) itself;
{
ptr = &b;
}
void modify_by_refrence(int * &ptr) //this function has refrence and hence can modify the pointer;
{
ptr = &b;
}

用双指针代替引用有什么好处?这个东西应该用在什么地方

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com