您的位置:首页 > 其它

指针修改变量的值,以及指针交换两个数字的值的问题

2016-12-26 11:04 375 查看
#include <iostream> 

using namespace std;

// 可以实现交换数值,但是不知道为什么?

//先读完程序然后告诉你。

void swap(int *a,int *b){
int *t;
t=a;
a=b;
b=t;

}

void main(){
int a=10;
int b=20;
swap(&a,&b); //不能实现交换
swap(a,b);
cout<<a<<endl;   //20
cout<<b<<endl;   //10
system("pause");

}

//答案就是:库函数的存在,你的函数名称和库函数名称一样了,那么这样默认调用的是库函数。
//这样实现了交换的两个数字值的功能,又没有调用自己写的方法。

//这个实际上改变的就是地址了。

void hah(int *a,int *b){
int *t=a;
a=b;
b=t;

}

int main() 


int a=10;
int b=20;
hah(&a,&b);
cout<<a<<endl;
cout<<b<<endl;

system("pause");



//不能交换两个数字的值

void swap1(int *a,int *b){
int *t;
t=a;
a=b;
b=t;

}

void main(){
int a=10;
int b=20;
swap(&a,&b); //不能实现交换
cout<<a<<endl;   //10
cout<<b<<endl;   //20
system("pause");

}

//通过引用改变两个数的值

void swap2(int &a,int &b){
int c=a;
a=b;
b=c;

}

int _tmain(int argc, _TCHAR* argv[])

{
int a=10;
int b=20;
swap(a,b);
cout<<a<<endl;   //20
cout<<b<<endl;   //10
system("pause");

}

//通过指针改变变量的值

void fun1(int *p){
(*p)++;

}

void main(){
int a=100;
fun1(&a);
cout<<a<<endl;//101
system("pause");

}

//实现地址的移动

void fun2(int *&a){
++a;

}

void main(){
int a=100;
int *b=&a
fun1(b);
cout<<a<<endl;//100
cout<<b<<endl;//输出的内容不确定
system("pause");

}

//通过引用改变值

void fun3(int &a){

 ++a;

}

int main(){
int a=100;
fun3(a);
cout<<a<<endl;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: