这个问题在这里已有答案:
/输入的数字应交换并显示。根据我的说法,这个简单的程序看起来不错,但事实并非如此。我尝试使用printf(“%d%d”)它可以工作,但在堆栈上使用默认值。但它没有使用这个代码。我尝试过不同的编译器,如TurboC ++,CodeBlocks(GCC)。有人可以帮我解释一下吗?提前致谢/
#include <stdio.h>
#include <stdlib.h>
void swap(int,int );
int main()
{
int x,y;
printf("Two Numbers: ");
scanf("%d\n%d",&x,&y);
swap(x,y);
printf("%d%d",x,y);//printf("%d%d"); makes the program work but not genuinely
return 0;
getch();
}
void swap(int x,int y)
{
int temp;
temp=y;
y=x;
x=temp;
}
您只是更改仅存在于方法交换中的x,y的值。 swap方法创建的对象x,y仅具有交换方法的新内存映射。它们不存在于方法交换之外。您需要传递值的内存地址引用,以便对原始值的内存地址执行操作。 Swap需要接受值的内存引用并将它们存储在指针中,这些指针将对原始值的内存位置执行操作。
#include <stdio.h>
#include <stdlib.h>
void swap(int*,int* );
int main()
{
int x,y;
printf("Two Numbers: ");
scanf("%d\n%d",&x,&y);
swap(&x,&y);
printf("%d%d",x,y);//printf("%d%d"); makes the program work but not genuinely
return 0;
}
void swap(int *x,int *y)
{
int temp;
temp=*y;
*y=*x;
*x=temp;
}
兄弟,正确的代码是这样的,
#include <stdio.h>
#include <stdlib.h>
void swap(x,y);
int main()
{
int x,y;
printf("Two Numbers: ");
scanf("%d\n%d", &x, &y);
swap(x,y);
//If you put print("%d%d", x, y); here it will not print swapped value because the swap(x,y) function only passing the value of x,y...
return 0;
getch();
}
void swap(int x,int y)
{
int temp;
temp=y;
y=x;
x=temp;
printf("%d%d",x,y);
}