C指针编程之道 ---第十一次笔记

来源:互联网 发布:手机做笔记软件 编辑:程序博客网 时间:2024/05/16 19:36

这次来说交换函数的实现:


1、


#include <stdio.h>#include <stdlib.h>void swap(int x, int y){int temp;temp = x;x = y;y = temp;}int main(){int a = 10, b = 20;printf("交换前:\n a = %d, b = %d\n", a, b);swap(a, b);printf("交换后:\n a = %d, b = %d", a, b);return 0;}//没错你的结果如下,发现没有交换成功,//是因为你这里你只是把形参的两个变量交换了,//然后函数执行完毕后你就把资源释放了,而没有实际改变实参。



那么用指针实现:#include <stdio.h>#include <stdlib.h>void swap(int *x, int *y){int temp;temp = *x;*x = *y;*y = temp;}int main(){int a = 10, b = 20;printf("交换前:\n a = %d, b = %d\n", a, b);swap(&a, &b);printf("交换后:\n a = %d, b = %d", a, b);return 0;}




//还有一种方式就是“引用 ”如下的sawp(&a, &b)//这里是c++的代码,如果你在c语言的代码里//使用这种引用的方式就会报错。#include <cstdio>#include <iostream>using namespace std;void swap(int &x, int &y){int temp;temp = x;x = y;y = temp;}int main(){int a = 10, b = 20;printf("交换前:\n a = %d, b = %d\n", a, b);swap(a, b);printf("交换后:\n a = %d, b = %d", a, b);return 0;}

0 0
原创粉丝点击