1.首先看一下指针如何进行算术运算:
#include<iostream>
using namespace std;
int main()
{
double wages[3] = { 10000.0,20000.0,30000.0 };
short stacks[3] = { 3,2,1 };
double* pw = wages;
short* ps = &stacks[0];
cout << "pw=" << pw << ",*pw=" << *pw << endl;
pw = pw + 1;
cout << "add 1 to the pw pointer." << endl;
cout << "pw=" << pw << ",*pw=" << *pw << endl;
cout << "ps=" << ps << ",*ps=" << *ps << endl;
ps = ps + 1;
cout << "add 1 to the ps pointer." << endl;
cout << "ps=" << ps << ",*ps=" << *ps << endl;
cout << "stacks[0]=" << stacks[0] << ",stacks[1]=" << stacks[1] << endl;
cout << "*stacks=" << *stacks << ",*(stacks+1)=" << *(stacks + 1) << endl;
cout << "sizeof(wages)=" << sizeof(wages) << endl;
cout << "sizeof(pw)=" << sizeof(pw) << endl;
return 0;
}
从以上程序可知,*(stacks+1)和stacks[1]是等价的。
数组与指针的区别:
- 指针的值是可以修改的,而数组名却为常量。
- sizeof在用于数组名的时候,不会将其解释为地址。
另外,对数组取地址时,数组名也不会被解释为其地址,数组名被解释为其第一个元素的地址,而对数组名应用地址运算符时,得到的是整个数组的地址。
short tell[10];//tell an array of 20 bytes
cout<<tell<<endl;//displays &tell[0]
cout<<&tell<<endl;//displays address of whole array
如下代码显示了数组的地址:
#include<iostream>
using namespace std;
int main()
{
short tell[10] = { 1,2,3,4,5,6,7,8,9,10 };
cout << "tell=" << tell << endl;
cout << "tell+1=" << tell + 1 << endl;
cout << "&tell+1=" << &tell + 1 << endl;
cout << "&tell+2=" << &tell + 2 << endl;
return 0;
}
另外,
short *pas[20];//pas为数组,且数组中的每个元素都是short类型的指针。
short (*pas)[20];//pas为指针,指向一个数组,数组中的每个元素都是short类型。 2. 给指针赋值。
应将内存地址赋给指针,可以对变量名应用&运算符,来获得被命名的内存地址,new运算符返回未命名的内存地址。
3.对指针解除引用。
对指针解除引用意味着获得指针的值,对指针应用解除引用或间接运算符(*)来解除引用。
cout<<*pn;//print the value of bubble
*pc='S';//place 'S' into the memory location whose address is pc
另一种解除引用的方法是使用数组表示法,例如pn[0]与*pn是一样的,不要对未被初始化为适当地址的指针解除引用。
4.区分指针与指针所指向的值。
如果pt是指向int的指针,则*pt不是指向int的指针,而是完全等同于一个int类型的变量。
5.数组名。
C++在多数情况下可将数组名是为数组的第一个元素的地址。在sizeiof情况下例外。
6.指针算术。
C++允许指针和整数相加,加1的结果等于原来的地址值加上指向的对象占用的总字节数。还可以将一个指针减去另一个指针,获得两个值针的差值。
7.数组的静态联编和动态联编。
使用数组声明来创建数组时,将采用静态联编,即数组的长度在编译阶段设置。
如:int tacos[10];
使用new[]运算符创建数组时,采用动态联编,即在运行时为数组分配内存空间,使用完用delete释放掉。