This question already has answers here:
Closed last year.
Simple swap function…why doesn't this one swap?
(12个答案)
/应交换并显示输入的数字。这个简单的程序在我看来很好,但事实并非如此。我试过使用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方法的新内存映射。它们不存在于方法交换之外。您需要传递值的内存地址引用,以便对原始值的内存地址执行操作。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;
}

关于c - 在C中使用功能NOT WORKING交换程序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52197120/

10-13 08:21