用函数交换变量不会影响调用站点 [英] Swapping variables with a function doesn't affect the call site

查看:24
本文介绍了用函数交换变量不会影响调用站点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几节课前我学习了变量,在我的作业中遇到了一个关于交换两个数字的问题 - 我使用第三个变量来解决这个问题.

A few lessons ago I learned about variables, and got a question in my homework about swapping two numbers - I used a third variable to solve this question.

解决方案看起来有点像这样:

The solution looked somewhat like this:

#include <stdio.h>

int main(void) {
    int x, y;
    scanf("%d %d", &x, &y);

    // swappring the values

    int temp = x;
    x = y;
    y = temp;

    printf("X is now %d and Y is now %d", x, y);
}

现在我正在学习函数,我想尝试使用辅助交换函数来解决前面的问题.

Now I'm learning about functions, and I wanted to try and solve the previous question with a helper swap function.

这是我写的代码:

#include <stdio.h>

void swap(int x, int y) {
    int temp = x;
    x = y;
    y = temp;
}

int main(void) {
    int a = 3, b = 4;
    swap(a, b);

    printf("%d %d\n", a, b);
}

我不知道为什么,但即使我更改了 swap() 函数中的值,输出仍然是 3 4.

I don't know why, but the output is still 3 4 even though I changed the value inside the swap() function.

为什么会这样?

推荐答案

xy 的地址作为参数传递给函数.现在它们是局部变量,不会对原始变量进行更改.

Pass address of x and y as arguments to function. Right now they are local variables, changes are not made to original variables .

做如下-

void swap(int *x,int *y){
 /*            dereference pointers and  swap    */
 int temp = *x;
 *x = *y;
 *y = temp;
}

然后像这样调用 main -

swap(&x,&y);

这篇关于用函数交换变量不会影响调用站点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆