2

我试图用指针交换两个整数......

#include<stdio.h>
int main()
{
int a,b,*i,*j;
printf("Enter two integer:");
scanf("%d%d",&a,&b);
i=&a;
j=&b;
a=*j;
b=*i;
printf("\n %d \t %d",a,b);
return 0;
}

输入是

12 45

输出是

45 45

经过一些试验,我发现如果我分配第b=*i一个然后分配a=*j,第一个整数即12重复..

为什么会这样?在我对指针的理解中,这就是我所做的。我已将*j(即存储在地址中的变量的值a)分配给b*i(即存储在地址中的变量的值b)分配给a..

请解释这个程序中真正发生的事情..

4

6 回答 6

4

从概念上讲,这就是您想要做的:

int temp = a; //temp <- 12
a = b;        //a <- 45
b = temp;     //b <- 12

从概念上讲,这就是您正在做的事情:

a = b; //a <- 45
b = a; //b <- 45

如果您使用 C++11,则可以“优雅地”执行此操作:

std::tie(b, a) = std::make_tuple(a, b);
于 2013-10-26T18:12:15.243 回答
3

这就是发生的事情:

i=&a; //i points to a
j=&b; //j points to b
a=*j; //assign the value of b to a
b=*i; //assign the value of a, which has been assigned to the value of b in the previous step

这是一种解决方法:

int temp = a;
a = b;
b = temp;
于 2013-10-26T18:15:14.933 回答
3

简单:

#include<iterator>
std::iter_swap(i,j);

或者确实

#include<algorithm>
std::swap(a,b);

或者对于纯粹主义者

using std::swap;
swap(a,b); // allow for ADL of user-defined `swap` implementations
于 2013-10-26T18:17:22.320 回答
2
a=*j;
b=*i;

i指向a后第一个语句a值的地址成为45,下一个赋值absob也成为45

      addressof `a` 
      ^
i-----|

      addressof 'b' 
      ^ 
j-----|

现在,当您对 a取消引用的值 进行更改时,i 也会发生更改。

只需使用临时变量

int temp;
temp=*i;
*i=*j;
*j=temp;
于 2013-10-26T18:12:08.977 回答
2
i=&a; //i points to a
j=&b; //j points to b
a=*j; // this statement is equvivalent to a = b; (since *j and b both are same)
so a = 45;
now
b=*i; // this statement is equvivalent to b = a; (since *i and a both are same) 
but a value is changed to 45 in previous statement, so the same 45 is assigned to b variable also 

你可以使用临时变量

于 2013-10-26T19:13:11.467 回答
0

这是因为 i 指向 a,所以一旦你给 a 赋值,存储在 a 中的原始值就会丢失。您可以引入第三个变量 temp 来存储分配之间的值(如发布的答案之一),或者做一些技巧,比如

a=a+b;
b=a-b;
a=a-b;

避免使用第三个变量。

编辑 此技术仅适用于无符号整数类型。

于 2013-10-26T18:14:13.257 回答