Possible Duplicate:
Why do these swap functions behave differently?
看看下面的代码,旨在交换两个数字,但事实并非如此。请帮助我理解为什么不这样做的原因。我是编程新手,所以如果您比平常更详细地解释这些事情,我将不胜感激。 谢谢!
#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 是按值传递的,因此 swap
函数接收值的副本,并且不会影响调用方中的变量。
要影响调用者中的变量,您需要向它们传递指针。
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
并命名它
swap(&x, &y);
在主
中。
关于c - 为什么这段代码不交换数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13543218/