2016-09-30 96 views
0

我想我的運氣在這個交換功能,但我有問題。交換功能和一般功能

我希望「num1」應該換成num2的值,反之亦然。

任何人都可以把我推向正確的方向嗎?

#include <stdio.h> 


void swap(int *a, int *b) 
{ 
int temp = *a; 
a = *b; 
b = temp; 
printf("Just checking if this badboy gets to the swapfunction.\n"); 
} 


int main() 
{ 
int num1 = 33; 
int num2 = 45; 

swap(&num1, &num2); 

printf("A: %d\n", num1); 
printf("B: %d\n", num2); 

getchar(); 
return 0; 
} 
+2

您應該收到來自編譯器的錯誤/警告消息,告訴您哪些線路有問題。如果不是,那麼你需要查看你的編譯器使用的設置。 –

+0

嗨,謝謝,它在我以正確的方式使用*時起作用。 不,它並沒有提醒我,它只是按原始順序打印出原始數字。我在哪裏可以管理這樣的設置? – niyz

+0

取決於你正在使用的編譯器和IDE ... –

回答

2

您需要尊重指針:

int temp = *a; 
*a = *b; 
*b = temp; 

沒有你的編譯器警告你?

+0

嗨,謝謝,它在我以正確的方式使用*時起作用。不,它沒有提醒我,它只是按原始順序打印出原始數字。我在哪裏可以管理這樣的設置? – niyz

+0

如果您使用GCC'-Wall'將啓用所有警告。有一些更細粒度的選項,請參閱https://gcc.gnu.org/onlinedocs/gcc/Option-Summary.html中的「警告選項」 – jayjay

0

你應該知道一些重要的事情是:需要

int temp = *a; // Correct , temp stores value at the address of a 

a = *b; //Incorrect, a is pointer that is used to hold address NOT values 

更正爲:

*a = *b; //Correct, now value at address of a is = value at address of b 

同樣的錯誤,在這裏也:

b = temp;//Incorrect, cause b is pointer used to hold address and NOT values 

進行糾正是

*b = temp;