1

I have question about line #2 and #9 of this code.
I have ran this code on codeblocks and it turns out that trip(&y) runs and make y=21 at the end of line 9. This is not what I expected.

I thought &y would return the address (like hexadecimal number) and pass it to trip. Then trip will triple the weird (hexadecimal) number of the address and perhaps change the address of int y, or produce error.

Which part of my logic has fault?

My logics are:

  1. &y returns the address of the variable (hexadecimal).
  2. trip (int* x) takes in the number (address in this case) and triples it.
  3. Therefore, nothing has been done to the actual value of y, which is 7.

midterm1

Edit: The answer is 105.

underdisplayname
  • 273
  • 3
  • 14

1 Answers1

2

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>.

sbecker
  • 553
  • 4
  • 12