我想知道调用如下方法有什么区别:
int x;
mymethod(x);
和
mymethod(&x);
最佳答案
因为 C 总是按值调用,如果您希望函数能够更改函数本身内部的 x,则必须传递 x 的地址。
mymethod(x);
将传递 x,例如,如果 x 是 2,您也可以编写 mymethod(2)
mymethod(&x)
将把地址传递给 x。现在该方法可以更改存储在该地址的值,因此函数完成后,x 的实际值可能已更改。
现在您还可以声明一个指针:
int* y; //y is now a pointer to a memory address
y = &x; //y now points to the memory address of x;
*y = 5; will set the "value found at the address y" to 5, thus will set x to 5;
关于c - C 中 mymethod(i) 和 mymethod(&i) 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5210241/