我在这个交换功能上试试运气,但我遇到了问题。
我的希望是"新的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;
}
答案 0 :(得分:2)
你需要 deference 指针:
int temp = *a;
*a = *b;
*b = temp;
你的编译器没有警告过你吗?
答案 1 :(得分: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;