1.为了交换a和b的值,将a,b的地址作为函数参数传递
2.实例代码:
#include <iostream>
using namespace std;
//指针变量作为函数参数的例子
void swap(int *m, int *n) //*m,*n,不是指针所指向的值
{
int temp;
temp = *m;
*m = *n;
*n =temp;
}
int main()
{
int a=5, b=10;
cout<<"a="<<a<<" b= "<<b<<endl;
cout<<"&a的地址 "<<&a<<endl;
cout<<"&b的地址 "<<&b<<endl;
swap(&a, &b);
cout<<"a="<<a<<" b= "<<b<<endl;
cout<<"&a的地址 "<<&a<<endl;
cout<<"&b的地址 "<<&b<<endl;
}
运行结果代码:
a=5 b= 10
&a的地址 0x28fefc
&b的地址 0x28fef8
a=10 b= 5
&a的地址 0x28fefc
&b的地址 0x28fef8
3.主要的问题,main()
函数中引用swap()
中传的参数是该变量对应的地址,而swap()
函数中却是用(int *m, int *n)
来接受的,不是特别明白,最后的地址也没有交换,只是交换了地址对应的值。
4.希望可以帮忙解决本问题,并在本问题的基础上,对于我认识的地址和指针的概念一些拓展,或者推荐相关的优秀的文章的url
,提前谢谢。
伊谢尔伦2017-04-17 14:53:22
Pointers are also variables and store the address of the variable. Variables can be accessed using variables or variable pointers. You need to exchange the value of the variable, you need to pass the address, and you can't just pass the value. In addition, the book "C and Pointers" is okay.
黄舟2017-04-17 14:53:22
First, please write the parameters as int* m
, and the type is int*
.
Addresses will not be exchanged because the address is where the variable value is located. Because m
and n
are pointer variables, they store addresses. *m
is to retrieve the value pointed to by the address stored in m
. So *m
and *n
are interchanged, not m
and n
.