青少年编程知识记录 codecoming

指针(三):指针与函数

1.交换的例子

#include<iostream>  #include<cstdio>  #include<cstring>  using namespace std;  void swap(int x, int y){  	int a=x;  	x=y;  	y=a;  	cout<<"函数内部"<<x<<" "<<y<<endl; // 4 3  }  int main() {  	int a=3,b=4;  	swap(a,b);  	cout<<a<<" "<<b<<endl;  // 3 4  	return 0;  }

上面的程序不能完成交换

而下面的程序可以完成交换

#include<iostream>  #include<cstdio>  #include<cstring>  using namespace std;  void swap(int &x, int &y){  	int a=x;  	x=y;  	y=a;  	cout<<"函数内部"<<x<<" "<<y<<endl; // 4 3  }  int main() {  	int a=3,b=4;  	swap(a,b);  	cout<<a<<" "<<b<<endl;  // 4 3  	return 0;  }

2.指针作为函数参数

#include<iostream>  #include<cstdio>  #include<cstring>  using namespace std;  void swap(int *x, int *y){  	int t =*x;  	*x= *y;  	*y=t;  	cout<<*x<<" "<<*y<<endl; // 4 3  }  int main() {  	int a=3,b=4;  	swap(&a,&b);  	cout<<a<<" "<<b<<endl;  // 4 3  	return 0;  }

上面的这样的例子可以完成交换。

下面的例子可以直接修改原来数据的值

#include<iostream>  #include<cstdio>  #include<cstring>  using namespace std;  void swap(int *x, int *y){  	*x=5;   }  int main() {  	int a=3,b=4;  	swap(&a,&b);  	cout<<a<<" "<<b<<endl;  //5 4  	return 0;  }





.jztagtree{max-height:85vh;right:0px}.jzDown{top:10vh}.jztagtree li a{background-color:#448EF6}.jztagtree li a:before{border-right:10px solid #448EF6}.jztagtree li a:hover{background:#0045a6}.jztagtree li a:hover::before{border-right:10px solid #0045a6}

    $("#jztoc").toc({content: ".single", headings: "h1,h2,h3"});

    作者:亿万年的星光 分类:C++目录 浏览: