2016-09-30 100 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;