为什么这个code不换号码? [英] Why does this code not swap the numbers?

查看:86
本文介绍了为什么这个code不换号码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  为什么这些交换功能表现不同?


有一个看看下面的code,旨在交换两个数字,但事实并非如此。请帮助我理解为什么它没有理由。我是新来编程,所以如果你解释比平时更多的事情,我将不胜感激。
谢谢!

 的#include<&stdio.h中GT;
无效掉期(INT A,INT B);
INT主要(无效)
{
   INT X = 1;
   INT Y = 2;
   交换(X,Y);
   的printf(现在x是%d个和y为%d \\ n,X,Y);   返回0;}
//功能互换的定义
无效掉期(INT A,INT B)
{
   INT TEMP =一个;
   诠释A = B;
   INT B =温度;
}


解决方案

C是通过按值,所以交换函数接收值的副本,而不能影响呼叫者的变量。

要影响到呼叫者的变量,你需要的指针传递给他们。

 无效掉期(INT *一,为int * B){
    INT TEMP = *一个;
    * A = * B;
    * B =温度;
}

和调用它

 交换(安培; X,&安培; Y);

Possible Duplicate:
Why do these swap functions behave differently?

Have a look at the code below, aimed to swap two numbers, but it does not. Please help me to understand the reason why it does not. I am new to programming, so I would be grateful if you explain the things more than usual. Thank you!

#include <stdio.h>
void swap (int a, int b);
int main (void)
{
   int x = 1;
   int y = 2;
   swap (x, y);
   printf ("Now x is %d and y is %d\n", x, y);

   return 0;

}
//function definition of swap
void swap (int a, int b)
{
   int temp = a;
   int a = b;
   int b = temp;
}

解决方案

C is pass-by-value, so the swap function receives copies of the values, and cannot affect the variables in the caller.

To affect the variables in the caller, you need to pass pointers to them.

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

and call it

swap(&x, &y);

in main.

这篇关于为什么这个code不换号码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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