考虑以下程序:
void f2 ( int * a, int * b) {
int c;
c = * a;
*a = *b;
*b = c;
}
int main () {
int a = 4, b = 5, c = 6;
f2 (&b, &c);
printf ("%d", c - a - b);
}
这里 b
和 c
的值正在交换。
另一个代码是:
# include <stdio.h>
void mystery (int *ptra, int *ptrb) {
int *temp;
temp = ptrb;
ptrb = ptra;
ptra = temp;
}
int main () {
int a = 2016, b=0, c= 4, d = 42;
mystery (&a, &b);
if (a < c)
mystery (&c, &a);
mystery (&a, &d);
printf("%d\n", a);
}
这里,虽然存在相同类型的函数调用,但 main()
程序中任何变量的值都没有改变。
众所周知,C 代码中没有引用调用。所以,我的问题是,虽然两个程序中都有相同类型的函数调用,但为什么一个程序交换变量的值而另一个程序不能交换?
在第二个程序中,指针交换意味着地址也交换。正确的??但不影响值(value)。在第一个程序中,地址和指针被交换,同时值也被交换。但为什么??
我也想知道,在哪里通过值调用,可以改变main()程序的值(带或不带返回函数)??
最佳答案
In the second program pointer is swapping means address are also swapping. Right?? But it doesn't affect on value. While in 1st program , address and pointer is swapped and at the mean time values also swapped. But Why??
因为
void mystery (int *ptra, int *ptrb) {
int *temp;
temp = ptrb;
ptrb =ptra;
ptra = temp;
}
上面的程序交换了ptra
和ptrb
的内容,而不是交换了ptra
和ptrb
的对象的内容指向,因为 ptra
和 ptrb
是 mystery
函数的本地函数。
以图形方式表示它。
考虑a
和b
存储在地址100
和200
。
神秘 (&a, &b);
调用之后。
ptra
将通过存储 100
来指向 a
。
并且 ptrb
将通过存储 200
来指向 b
。
ptra 100
+-----+ +---+
| 100 | | 1 |
+-----+ +---+
ptrb 200
+-----+ +---+
|200 | | 2 |
+-----+ +---+
当函数完成执行时。
ptra
将通过存储 200
来指向 b
。
并且 ptrb
将通过存储 100
来指向 a
。
ptra 100
+-----+ +---+
| 200 | | 1 |
+-----+ +---+
ptrb 200
+-----+ +---+
|100 | | 2 |
+-----+ +---+
关于按值调用可以改变主程序的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56905755/