You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言两数交换代码问题:仅一个数值交换成功,另一数值异常

问题分析与修复:交换整数的C语言函数错误

你的核心问题出在swap函数的逻辑错误,以及使用了未初始化的局部变量,导致交换失败且y出现随机值(比如你看到的-2)。

错误原因拆解

原swap函数的代码逻辑完全颠倒:

void swap(int *a , int *b){
    int temp;
    *a = temp;  // 这里把未初始化的temp(随机垃圾值)赋值给*a,直接覆盖了原x的值
    *a = *b;    // 把*b的值赋给*a,这一步让x变成了y的原始值,所以你看到x交换成功
    *b = temp;  // 把未初始化的垃圾值赋给*b,也就是main里的y,所以y变成随机数-2
}

temp是局部变量,未初始化时会保留栈上的随机数据,这就是y输出-2的原因。

修复后的正确代码

交换两个值的标准逻辑是先保存其中一个值,再依次覆盖,修正后的代码如下:

#include<stdio.h>

void swap(int *a , int *b){
    int temp = *a; // 先保存a指向的原始值(也就是main里的x)
    *a = *b;       // 把b指向的值(y的原始值)赋给a指向的变量(x)
    *b = temp;     // 把保存的原始x值赋给b指向的变量(y)
}

int main()
{
    int x,y;
    printf("enter the first number : ");
    scanf("%d" , &x);
    printf("enter the second number : ");
    scanf("%d" , &y);

    printf("the value of x and y before swap are %d and %d and the address of x and y are %p and %p\n" , x , y , (void*)&x , (void*)&y);
    swap(&x , &y);
    printf("the value of x and y after swap are %d and %d and the address of x and y are %p and %p\n" , x , y , (void*)&x , (void*)&y);
    return 0;
}

另外补充一个小细节:打印地址时用%p格式符更规范,同时需要把地址强制转换为void*类型,这是C标准要求的。

内容的提问来源于stack exchange,提问作者DANAB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 07:09:40