按值调用可以改变主程序的值

Call by value can change the value for main program

考虑以下程序:

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);  
 }

此处 bc 的值正在交换。

另一个代码是:

# 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代码中没有引用调用。所以,我的问题是,虽然两个程序中都有相同类型的函数调用,但为什么一个交换变量的值而另一个不能交换??

在第二个程序中指针在交换意味着地址也在交换。正确的??但不影响价值。在第一个程序中,地址和指针被交换,同时值也被交换。但是为什么??

我也想知道,按值调用哪里可以改变main()程序的值(带或不带return函数)??

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; 
}

上面的程序交换了 ptraptrb 的内容,而不是 ptraptrb 指向的对象的内容,因为 ptraptrbmystery 函数的局部变量。


形象地表示。

考虑 ab 存储在地址 100200.

mystery (&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 | 
   +-----+     +---+

在第一个片段中,您更改了此函数范围内非本地对象的值 - 在 main 中定义并由这些指针引用。

在第二个中,您将退出函数时停止的局部变量更改为存在。

在第一个程序的 f2 中,指针被 取消引用 以更改这些指针指向的内容,以便 bcmain函数中进行了修改。相反,第二个程序中的 mystery 只是交换局部变量 ptraptrb 的值,这对 main.[=27= 中的变量没有影响]

所以这个:

ptrb = ptra; 

将一个指针的值赋给另一个指针(它们都是 msytery 的本地指针),而这:

*a = *b;

将一个指针指向的值更改为另一个指针指向的值,即a bmain.

另一种思考方式是房屋及其居民:

    ______        _____         ______       ______
   /______\      /______\      /______\     /______\
 2 |Smith |    4 |Jones |    6 | Bond |   8 | Solo |
   --------      --------      --------     --------

第一个程序说 "swap the residents of two houses":

    ______        _____         ______       ______
   /______\      /______\      /______\     /______\
 2 |Smith |    4 | Bond |    6 |Jones |   8 | Solo |
   --------      --------      --------     --------

虽然第二个在说 "swap the numbers on the houses":

    ______        _____         ______       ______
   /______\      /______\      /______\     /______\
 2 |Smith |    6 |Jones |    4 | Bond |   8 | Solo |
   --------      --------      --------     --------