方法一:
int a = 5, b = 6;
int temp = a;
a = b;
b = temp;
方法2:
int a = 5, b = 6;
int *p = a;
a = b;
b = p;
方法3:
int a = 5, b = 6;
a = a + b;
b = a - b;
a = a - b;
考虑到内存管理,有没有有效的方法来解决这个交换问题
对于交换,您可以使用
swap
函数并通过引用传递。即在调用函数中,值在指针中更改,而不是多次复制。
void swap(int *a, int *b){
int temp = *a; //temp is on stack memory. i.e. local variable
*a = *b;
*b = temp;
}
int main(){
int a = 5, b = 7;
swap(&a, &b);
return 0;
}