-1

我编写了这个程序来使 b 中的 a 值和 a 中 b 的值。

为此,我创建了 temp 作为临时变量,这是我的程序:

#include <stdio.h>

int changevalue(int a, int b)
{
    int temp;
    temp = a;
    a = b; 
    b = temp;
}

int main()
{
    int a;
    int b;
    a = 10;
    b = 20; 
    printf("the value of a is %d \n and b is %d",a,b);
    changevalue(a,b);
    printf("the value of a is %d \n and b is %d",a,b);
    return 0;
}

但是 a 和 b 的值没有改变。

问题出在哪里?

4

1 回答 1

3

您需要使用指针:

#include <stdio.h>

void changevalue(int *a, int *b)
{
    int temp;
    temp = *a;
    *a   = *b; 
    *b   = temp;
}

int main()
{
    int a=10;
    int b=20;
    printf("the value of a is %d \n and b is %d",a,b);
    changevalue(&a,&b);
    printf("the value of a is %d \n and b is %d",a,b);
    return 0;
}
于 2020-10-09T13:04:55.213 回答