提问人:DANAB 提问时间:1/24/2023 更新时间:1/24/2023 访问量:58
我写了一个代码来交换两个号码,但只有一个号码被交换了 [已关闭]
I wrote a code to swap two numbers but only one of the numbers gets swapped [closed]
问:
#include<stdio.h>
void swap(int *a , int *b){
int temp;
*a = temp;
*a = *b;
*b = temp;
}
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 %u and %u\n" , x , y , &x , &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 %u and %u\n" , x , y , &x , &y);
return 0;
}
我试图交换数字,而 X 的值与值 Y 交换,但 Y DOSENT 的值与 X 交换,它在输出中显示 -2。
答:
1赞
Gabriel
1/24/2023
#1
void swap(int *a , int *b){
int temp;
temp = *a;
*a = *b;
*b = temp;
}
temp
必须不是 必须*a
*a
temp
评论
*a = temp;
temp = *a;
int temp; *a = temp;
该变量未初始化,因此您只是用不确定的值覆盖了指向的内容。temp
a