jefazo92 wrote: |
---|
I don't understand your answer to the 2nd question. As far as I have always undertood you can modify where the ppointer is pointing at and the value of the variable it's pointing at. But from what you are saying when passing a pointer by value:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
main(){
int x=5;
*p=x;
myfunction(p);
return 0;
}
myfunction(p)
{
int y=7;
*p=y;
return (p)
}
|
Would be llegal ? |
(Indentation added by me)
That code is illegal for all sorts of reasons. You haven't defined defined any of the variables called
p, not have you given
p a value in
main().
p doesn't point to anything, so when you try and dereference it using
*p
, you'll have undefined behaviour - if you're lucky, it will cause a crash. Nor have you defined the return type of
myfunction.
But that's beside the point, I guess.
To turn it into legal C++, and assuming I understand the point you're trying to make, here's what you should have written:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
int main(){
int x=5;
int* p = &x;
std::cout << "The value of x before calling myfunction is " << x;
myfunction(p);
std::cout << "The value of x after calling myfunction is " << x;
return 0;
}
void myfunction(int* p)
{
int y=7;
*p=y;
// I don't know why you put this here, when you don't use the return value
// anywhere, and it obscures the whole point of using pointers to simulate
// passing by reference.
// return (p)
}
|
So, once we've made the code legal and sensible, this would behave the way you expect.
myfunction() would change the value of the thing
p is pointing to, and this change would be seen in
main() as a change to the value of of
x.
We call this "passing by reference", although that's not technically true. We're passing the value of
p - which is a pointer, remember - by
value, and then changing the value of the thing
p points to. The variable called
p in
myfunction() is a copy of the variable called
p in
main(). They both point to the same memory location, which means that when you change what's stored in that location in
myfunction(), and then look at what's stored at that location in
main(), you see the changed value.
So, although the pointer is passed by value, we can use it to simulate passing by reference the thing that the pointer is pointing to.
However, you're misunderstanding what jonnin said. You're talking about changing the value of the thing
p points to. He's talking about the value of
p itself. Passing
p as a reference allows the function to change the value of
p itself, and have that change be made to the value of
p in
main().