以下代码通过传递指针,交换两个变量的内容:
1 void swap(int* m, int* n) 2 { 3 4 int c; 5 c = *m; 6 *m = *n; 7 *n = c; 8 9 } 10 11 int main() 12 { 13 int m = 5 , n = 4; 14 swap(&m, &n); 15 printf("m = %d, n = %d ", m, n); 16 }
以下代码通过传递引用,交换两个变量的值:
1 #include<stdio.h> 2 #include "stdafx.h" 3 4 void swap(int &m, int &n) 5 { 6 7 int c; 8 c = m; 9 m = n; 10 n = c; 11 12 } 13 14 int main() 15 { 16 int m = 5 , n = 4; 17 swap(m, n); 18 printf("m = %d, n = %d ", m, n); 19 }
通过不开辟额外的内存空间来实现,元素的交换
1 #include<stdio.h> 2 #include "stdafx.h" 3 4 5 int main() 6 { 7 int m = 5 , n = 4; 8 m = n - m; 9 n = n - m; 10 m = m + n; 11 12 printf("m = %d, n = %d ", m, n); 13 return 0; 14 }