将变量传递给函数

索伯斯特

我对此代码的第2行和第9行有疑问。
我已经在代码块上运行了这段代码,结果证明它trip(&y)可以y=21在第9行的末尾运行和生成。这不是我期望的。

我以为&y会返回地址(如十六进制数字)并将其传递给trip然后trip将地址的奇数(十六进制)数增加三倍,并可能更改的地址int y,或产生错误。

我的逻辑哪一部分有问题?

我的逻辑是:

  1. &y 返回变量的地址(十六进制)。
  2. trip (int* x) 接受数字(在这种情况下为地址)并将其增加三倍。
  3. 因此,没有做任何事情来的实际价值y,这是7

期中1

Edit: The answer is 105.

sbecker

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

如果必须使用指针,请考虑使用像std::unique_ptr<T>一样的智能指针std::shared_ptr<T>

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章