您的位置:首页 > 编程语言 > C语言/C++

C++指针理解《一》

2016-04-02 13:36 351 查看
贴个代码,注释比较清楚了。对于局部指针变量的问题,参见http://ask.csdn.net/questions/246619,感谢这么多热心人回答这个问题。

#include<iostream>
using std::cin;
using std::cout;
using std::endl;
const int* pointParmas(const int *t);
int*& pointBoom();

int main()
{

int*a=NULL;
int d = 10;
int &c = d;//c是引用
cout << "d的值" << d<<endl;
cout << "d的地址" << &d<<endl;
cout << "c的值" << c<<endl;
cout << "c的地址" << &c<<endl;
a = &d;
cout << "实参a的值" << *a << endl;
cout << "实参a中存储的地址" << a << endl;
cout << "实参a的地址" << &a << endl;

cout << "调用函数pointParmas" << endl;
cout << *pointParmas(a)<<endl;
cout << "d的值" << d<<endl;
cout << "实参a的中存储地址" << a << endl;
cout << "实参a的地址" << &a << endl;

cout << "调用函数pointBoom" << endl;
cout << "pointBoom的值是" << *pointBoom() << endl;
cout << "pointBoom中返回的地址是" << pointBoom() << endl;

int s = 0;
cin >> s;

return 0;

}

const int* pointParmas(const int* t) //指针存储的是内存地址
{
cout << "形参t的中存储的地址" << t<<endl;
cout << "形参t的地址" << &t << endl;
int c = 20;
cout << "c的地址" << &c<<endl;
t =&c;
//*t = 30//编译时报错,左值必须可以修改,形参t是常量指针,const*int p这种类型,属于能修改指针指向的地址,但是不能修改指针指向的值
//补充int *const p能修改指针指向的值,但是不能改地址,在这个函数中,如果t属于这种类型旳指针,那么t&g就会报错
//const int *const p是最严格,既不能改值也不能改地址
//int g = 30;
//t = &g;
cout << "形参t中存储的地址" << t<<endl;
cout << "形参t的地址" << &t << endl;
return t;
}

int*& pointBoom()//局部变量指针测试
{
int c = 20;
int *f = &c;//局部变量指针f
cout << "局部变量c的地址" << &c<<endl;
cout << "局部变量f存储的地址" << f<<endl;
cout << "局部变量f的地址" << &f<<endl;

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