int a = 12;
int *p;
p = &a;
注意:p表示指针地址,*p是该地址内所存储的值。
当定义一个指针时, 计算机将只分配用来存储地址的内存,但不会分配用来存储指针所指向数据的内存。比如,以下代码就是错误的。
long *pl;
*pl = 123456;//place a value in never-never land, to which the pointer pl doesn't point
为此,可通过new来分配数据内存。
long *pl = new long;
但为了防止内存泄漏,用new定义的内存,都需要用delete来删除。在新版C++11中,可使用智能指针来防止内存泄漏,其将自动为我们执行删除new定义的内存。
delete pl;
再如
int *pArray = new int[10];
delete [] pArray;
对指针可以进行算术运算, 但对两个指针做加法等运算没有任何意义。
double *pd = new double[10];
pd = pd + 1; //now pd point to the second element of the array
使用指针创建动态结构struct s {
char charr[20];
float a;
double b;
};
int main() {
s *ps = new s; //allot memory for structure s
//4 methods for accessing the elements of the structure
cin.get(ps->charr, 20);
cin >> (*ps).a; //*ps here means the structure instance
cin >> ps->b;
cin >>ps->charr[5];
delete ps;
return 0;
}