C++学习笔记三之指针

来源:互联网 发布:淘宝直通车怎么收费 编辑:程序博客网 时间:2024/05/18 00:45

【解释说明】

int  p=12;

int *q;

int *q=&p;

这里p为int类型的变量,&p就是p的内存地址,*p是一个int类型的变量(是一个值),q为指针是地址,int *q=&p;把p的地址赋给了指针q,所以*q就等于p的值=12,而q=&p,因为指针本身也是变量,所以&q就是指针q的内存地址。

这里有一点要注意:

1、不能写成int *q=p;会报错int类型的值不能初始化int类型的实体。因为没有给int类型分配内存地址,可以先用new 分配内存然后再赋值,例如:

int *q=new int;

*q=p;

有了内存地址,然后再赋值就不会报错了。当然这里的q就不等同于&p了,是一个新地址。

还可以写成:

int *q;

q=&p;

反正就是要先分配内存地址,才能赋值。

【示例代码】

#include <iostream>#include <stdlib.h>int main(){using namespace std;int a = 6;int b = 4;cout << "a = " << a;cout << " and a address = " << &a << endl;int *p_b;p_b = &b;cout << "p_b:" << *p_b<<endl;cout << "*p_b+1:" << *p_b + 1 << endl;int d = 1001;int *pt = new int;*pt = 1001;cout << "d:" << d <<" and d adress:"<<&d<< endl;cout << "*pt:" << *pt << "pt:" << pt <<"&pt:"<<&pt<< endl;int e = 12;int *p_e=&e;//e=*p_e,p_e=&e,&p_e为指针变量p_e的地址int *q_e=new int;//给q_e分配新内存*q_e=e;cout << "e:" << e << " *q_e:" << *q_e << " q_e:" << q_e << " &q_e:" << &q_e << "&e:" << &e << endl;cout << "e:" << e << " *p_e:" << *p_e << " p_e:" << p_e << " &p_e:" << &p_e <<  "&e:" << &e << endl;e = e + 3;cout << "&(e+3):" << &e << endl;system("pause");return 0;}
【演示结果】





原创粉丝点击