指向指针的指针和指针的引用
2015-12-26 11:58
309 查看
当我们把一个指针作为一个参数传递给函数时,其实是把指针的copy传递给了函数,也可以说传递指针是指针的值传递。
如果我们在函数内部修改指针,修改的只是指针的copy而不是指针本身。代码验证如下:
指针的指针
在函数func中:
p是一个指针的指针
*p是被指向的指针,我们修改它,修改的是被指向的指针的内容,即main函数中的指针p
**p两次解引用是指向main函数的*p的内容
指针的引用
#include<iostream>
using namespace std;
int num1 = 1;
void func(int* &p)
{
p = &num1;
*p = 5;
cout << p << ' ' << *p << ' ' << num1 << endl;
}
int main()
{
int num2 = 2;
int *pnum2 = &num2;
cout << pnum2 << ' ' << *pnum2 << endl;
func(pnum2);
cout << pnum2 << ' ' << *pnum2 << endl;
return 0;
}
在func函数中:
p是指针的引用,即main函数里中的pnum2
*p是main函数中pnum2指向的内容
如果我们在函数内部修改指针,修改的只是指针的copy而不是指针本身。代码验证如下:
#include<iostream> using namespace std; int num1 = 1; void func(int* p) { p = &num1; cout << p << endl; cout << *p << endl; } int main() { int num2 = 2; int *p = &num2; cout << p << endl; cout << *p << endl; func(p); cout << p << endl; cout << *p << endl; return 0; }
指针的指针
#include<iostream> using namespace std; int num1 = 1; void func(int** p) { <span style="white-space:pre"> </span>*p = &num1; <span style="white-space:pre"> </span>**p = 5; <span style="white-space:pre"> </span>cout << p << ' ' << *p << ' ' << **p << ' ' << num1 << endl; } int main() { <span style="white-space:pre"> </span>int num2 = 2; <span style="white-space:pre"> </span>int *pnum2 = &num2; <span style="white-space:pre"> </span>cout << pnum2 << ' ' << *pnum2 << endl; <span style="white-space:pre"> </span>func(&pnum2); <span style="white-space:pre"> </span>cout << pnum2 << ' ' << *pnum2 << endl; <span style="white-space:pre"> </span>return 0; }
在函数func中:
p是一个指针的指针
*p是被指向的指针,我们修改它,修改的是被指向的指针的内容,即main函数中的指针p
**p两次解引用是指向main函数的*p的内容
指针的引用
#include<iostream>
using namespace std;
int num1 = 1;
void func(int* &p)
{
p = &num1;
*p = 5;
cout << p << ' ' << *p << ' ' << num1 << endl;
}
int main()
{
int num2 = 2;
int *pnum2 = &num2;
cout << pnum2 << ' ' << *pnum2 << endl;
func(pnum2);
cout << pnum2 << ' ' << *pnum2 << endl;
return 0;
}
在func函数中:
p是指针的引用,即main函数里中的pnum2
*p是main函数中pnum2指向的内容
相关文章推荐
- 中国铁建内网漫游沦陷多个重要部门泄漏大量信息(redis+ssh-keygen免认证登录案例)
- Spring 4 学习笔记3:依赖注入(DI)
- Shiro
- 排序算法总结
- 文件操作类
- Android互联网访问图片并在客户端显示的方法
- stl中std::binary_function的使用
- 有用的网址(php)
- handle
- CString转string
- Intellij Idea 主题下载(Eclectide Monokai)
- android 4.0 BLE开发官方文档介绍
- FreeMarker整合Spring mvc
- quick-cocos2d-x + Lua 开发
- java基础02
- Nginx/LVS/HAProxy负载均衡软件的优缺点详解
- C# 表复制和数据行的复制说明(Clone、ImportRow 、Copy )
- 指针
- SpringMVC获取http请求中的参数
- dubbo 教程