c/c++中容纳地址的变量称为指针类型的变量,其运算规则与指针指向的数据类型相关。
赋初值方式有两种(也可以用一个已经赋值的指针去初始化另一个指针)
如果用一个指针变量赋值为0,表示该指针为空指针。
int *p[3]; //首先从P 处开始,先与[]结合,因为其优先级比*高,所以P 是一个数组,然后再与*结合,说明数组里的元素是指针类型,然后再与int 结合,说明指针所指向的内容的类型是整型的,所以P 是一个由返回整型数据的指针所组成的数组,三个指针组成的数组
int (*p)[3]; //首先从P 处开始,先与*结合,说明P 是一个指针然后再与[]结合(与"()"这步可以忽略,只是为了改变优先级),说明指针所指向的内容是一个数组,然后再与int 结合,说明数组里的元素是整型的.所以P 是一个指向由整型数据组成的数组的指针,指向数组首地址的指针
基本用法(举个栗子)
#include<iostream>
using namespace std;
int main()
{
int num(23);
int *s=0;
int *p=0;//表明该指针是一个空指针,声明指针变量,这里的0表示空指针,不能是非零的常数
p=#//在声明之后,使用赋值化语句为指针赋值
s=p;
int *t=#//也可以声明指针变量时用变量地址进行初始化
cout<<"the integer is:"<<num<<endl;
cout<<"the num that is pointed to is:"<<*p<<endl;
cout<<"the address is"<<p<<endl;
cout<<*s<<endl;
cout<<*t<<endl;;
*p=24;//通过访问*p来改变数据的值
cout<<"the integer is:"<<num<<endl;
cout<<"the num that is pointed to is:"<<*p<<endl;
cout<<"the address is"<<p<<endl;
cout<<*s<<endl;
cout<<*t;
return 0;
}
运行结果:
the integer is:23
the num that is pointed to is:23
the address is0x69fef0
23
23
the integer is:24
the num that is pointed to is:24
the address is0x69fef0
24
24