0

What's different between declaring int **p and int **&p?

PPointer

10th Oct 2016, 2:02 PM
Quân Đỗ
Quân Đỗ - avatar
3 odpowiedzi
+ 3
I think the real question here is: what is the difference between an `int p` and an `int &p`? The difference here is that the first one is a value, while the second one is a reference, which makes them behave differently in the context of function parameters. Let's see them in action, since code says more than a thousand words: void value(int p){ p = 5; cout << p << endl; } void reference(int &p){ p = 5; cout << p << endl; } Let's also say we have a variable `int a = 4;`. What happens if we plug 'a' into the first function? value(a); cout << a << endl; You will see '5', then '4' pop up on the screen. Inside the function, we set our variable to something different and we get '5' as we'd expect, but the second cout will not know about the change at all and will still print '4'. This is because, if you pass by _value_, the function you call will get a fresh copy of whatever you pass in! And that's precisely so it doesn't mess with the original thing outside the function and everything is nice and tidy. Well, sometimes you don't want that, so there's also pass-by-reference: reference(a); cout << a << endl; You will see '5', followed by '5'. If you pass by reference, you don't get a copy but the real deal. The same goes for ordinary variables. Different example: int a = 4; int b = a; a = 10; cout << b << endl; Unsurprisingly, b doesn't change and is still 4, since b gets a copy of a. However, here: int a = 4; int &b = a; a = 10; cout << b << endl; You'll see '10', because you took a reference of 'a' instead of its value. Now, what's the difference between an 'int **p' and an 'int **&p'? The second one is a reference to the first - a reference to an 'int**'. These things get confusing once you throw pointers into the mix, so try to take it one step at a time :P
10th Oct 2016, 3:36 PM
Schindlabua
Schindlabua - avatar
+ 1
I hear you! Pointers are hard. It probably took me a year until I got pointers and pointers to pointers to pointers.. It's ok if you don't totally understand them right away, in everyday C++ you'll be mostly dealing with references anyway.
10th Oct 2016, 4:28 PM
Schindlabua
Schindlabua - avatar
0
thanks so much for helping me, i'm learning pointer and it's make me confused so much
10th Oct 2016, 3:46 PM
Quân Đỗ
Quân Đỗ - avatar