函数中引用指针。结果如下。
目录
代码1:
#include <iostream>
using namespace std;
void test(int * testnum)
{
(*testnum)+=5;
}
int main()
{
int n;
cin>>n;
test(& n);
cout<<n;
}
输入-输出:
101-106
102-107
105-110
1 - 6
代码2:
#include <iostream>
using namespace std;
void test(int * testnum)
{
(*testnum)*=2;
(*testnum)++;
}
int main()
{
int n;
cin>>n;
test(& n);
cout<<n;
}
输入-输出:
1-3
2-5
3-7
10-21
由多组数据可见,函数中调用指针进行操作后,指针的值将被更新并返回到main()函数中。
值得注意的是
main()调用指针需要加&;函数中调用指针,需要加()和*。(详见以上程序)。