簡體   English   中英

使用C中的指針交換兩個數字

[英]swapping two number using pointer in C

我嘗試使用指針交換兩個整數...

#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 ..

請解釋一下這個程序到底發生了什么......

從概念上講,這就是你想要做的:

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);

這是發生的事情:

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;

Simples:

#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
a=*j;
b=*i;

i點地址a第一條語句后a值成為45和未來分配ab因此b也成為45

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

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

現在,當你做出改變,以a被取消引用值,然后i也會改變。

只需使用臨時變量

int temp;
temp=*i;
*i=*j;
*j=temp;
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 

你可以使用temp變量

這是因為我指向a,所以只要你給a指定了東西,就會丟失存儲在a中的原始值。 你可以引入第三個變量temp來在賦值之間存儲值(比如在發布的一個答案中),或者做一些技巧

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

避免使用第三個變量。

編輯此技術僅適用於無符號整數類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM