指针是一个变量,其存储的是值得地址,而不是值本身。通过&name获取变量地址。
typename * name;name是指针(地址),*name是typename而不是指针int * p1,p2创建了一个指针(p1)和一个变量(p2),对每个指针变量名,都需要使用一个*int*是一种复合类型,是指向int的指针int * pt;pt=(int*)0xB8000000;pt是int值的地址并不意味着pt本身的类型是inttypeName * pointer_name=new typeName;int * ps =new int;delete ps;这将释放ps指向的内存,但不会删除ps本type_name * pointer_name = new type_name [num_elements];pointer_name[num]访问元素double wages[3]={1000.0,2000.0,3000,0};
double * pw =wages;
和所有数组一样,wages也存在下面的等式:wages=&wages[0]=address of first element of array
将指针变量加1后,其增加的值等于指向的类型占用的字节数*(pw+1)和pw[1]是等价的
short tell[10];short(*)[20]*pw和wages[i]的区别pw=pw+1;wages=wages+1;//not allowed&wages得到是整个数组的地址char food[20]="carrots";
strncpy(food,"a picnic basket filled with many goodies",19);
food[19]="\0";
.;如果标识符是指向结构的指针,则使用箭头运算符->struct inflatable
{
float volume;
double price;
};
inflatable * ps = new inflatable;
//通过ps->price或(*ps).price访问结构成员
delete ps;
struct antarctica
{
int year;
};
创建类型变量antarctica s01,s02,s03;
创建结构指针antarctica * pa = &s01;
创建指针数组const antarctica * arp[3]={&s01,&s02,&s03};
创建指向指针数组的指针const antarctica ** ppa = arp;=auto ppb = arp;
通过(*(ppa+i))->year访问结构中的元素
vector<typeName> name(size);array<typeName,size> arr;array<int,3> arr={1,2,3};vector<int> vec={1,2,3};vector<int> vec(3);//需要分别赋值让指针指向一个常量对象,防止使用该指针来修改所指向的值
int age =39;
const int * pt =&age;
*pt=20;//INVALID
age=20;//VALID
//可以直接通过age变量来修改age的值,但不能使用pt指针来修改它
将指针本身声明为常量,防止改变指针指向的位置
int sloth=3;
const int * ps = &sloth;
int * const finger = &sloth;
// finger和*ps都是const,而*finger和ps不是
double trouble = 2.0E30;
const double * const stick = &trouble;
//stick和*stick都是const