You are right about the address of y
that is given to the function trip(int*)
.
Your mistake is that the function trip(int*)
dereferences the address to access the value it points to.
Assume y
has the value 7 and is stored at address 0x0014 (simplified for your convenience).
The function trip(int*)
gets the address 0x0014 and uses it to get to the value 7 of y
.
Now it triples this value and stores the result where the address is pointing to. Thus overwriting the value 7 of y
with the new value of 21.
This dereferencing of the address is done by the star (*) right in front of the x
in the body of the function trip(int*)
.
To clarify. Addresses aren't necessarily a hexadecimal value. Hexadecimal is just a way to display a number. Addresses are just the number to a certain place in memory. In this case 0x0014 is the same as 20 in decimal. Meaning y
is stored at address 20 (as decimal).
Please keep in mind that pointers are rarely the right way to do something. Like in this case with the function quin(int&)
. The problem that is solved with a pointer in trip(int*)
, is solved much cleaner in quin(int&)
. References are cleaner and safer.
The function trip(int*)
does not check for the case that the address given is invalid (the address given is NULL
/nullptr
). quin(int&)
doesn't even have to check for this since references cannot be NULL
in C++.
If you have to use pointers, consider using smart pointers like std::unique_ptr<T>
and std::shared_ptr<T>
.