2015-01-11 43 views
1

好的。這可能是一個愚蠢的問題。使用指針交換字符變量

我想交換兩個字符變量使用pointers.following是我的代碼。

void swap_char(char* x, char* y) 
{ 
char *tmp=x; 
*x=*y; 
*y=*tmp; 

/* int t=*x; 
*x=*y;  // this works fine and i understand 
*y=t; 
*/ 

} 

和函數調用is--由X和Y兩個指出

swap_char(&s[0],&s[j]); // where s is std::string variable 

值是一樣的交換後,由Y指出值..

我就是我在做什麼錯在這裏

+2

你有什麼特別的理由使用指針?無論如何,您需要一個臨時變量,您可以在其中存儲要交換的兩個值之一。由於你的代碼只涉及指針,你沒有。 – juanchopanza

回答

1

tmpx指向同一位置char* tmp=x後,所以,當你寫

*x = *y; 

*tmp是也改變了。意味着後續的

*y = *tmp; 

是一個無操作。使用std::swap

+0

謝謝。這很清楚 – ssh99

3

您應該將x指向的值存儲在tmp中,而不是地址x本身(表示tmp應該是char)。

既然你tmp設置爲x,你的代碼基本上等同於:

*x = *y; 
*y = *x; 
1

我會根據您的原始代碼進行更改 - 以便您看到自己的錯誤。你應該做的是將x的「值」賦給tmp - 而不是指針本身。後者是你的tmp聲明/初始化會發生什麼。詳情內嵌代碼。

void swap_char(char* x, char* y) 
{ 
// char *tmp=x; // this would create a new tmp pointer and assign "tmp" with x - and NOT "*tmp" with *x". 
    char tmp = *x; // new code - store the VALUE pointed by x in tmp 
    *x=*y; // store VALUE pointed by y to storage pointed by x 
    *y=tmp; // modified to delete * from tmp - store VALUE of tmp to storage pointed by y 
} 
-1
void charSwap(char** a, char** b){ 
    char *temp = *a; 
    *a = *b; 
    *b = temp; 
} 

試試這個代碼。