文章目录
指针、数组和指针运算
指针和数组基本等价的原因在于指针算术( pointer arithmetic)和C++内部处理数组的方式。首先,我们来看一看算术。将整数变量加1后,其值将增加1;但将指针变量加1后,增加的量等于它指向的类型的字节数。将指向 double的指针加1后,如果系统对 double使用8个字节存储,则数值将增加8:将指向short的指针加1后,如果系统对 short使用2个字节存储,则指针值将增加2。下面程序演示了这种令人吃惊的现象,它还说明了另一点:C++将数组名解释为地址。
// addpntrs.cpp
#include <iostream>
int main()
{
using namespace std;
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;
cout << "add 1 to the pw pointer:\n";
pw = pw + 1;
cout << "pw = " << pw <<", *pw = " << *pw <<"\n\n";
cout << "ps = " << ps << ", *ps = "<<endl;
cout << "add 1 to the ps pointer:\n"
ps = ps + 1;
cout << "ps = " << ps <<", *ps = " << *pw <<"\n\n";
cout << "access two elements with array notation\n";
cout << "stacks[0]= " << stacks[0] << ", stacks[1] = " << stacks[1] << endl;
cout << "access two elements with pointer notation\n";
cout << "*stacks= " << *stacks << ", stacks[1] = " << *(stacks+1) << endl;
}
//程序输出
pw = 0x28ccf0,*pw = 10000
add 1 to the pw pointer:
pw = ox28ccf8,*pw = 20000
ps = ox28ccea,*ps = 3
add 1 to the ps pointer:
ps = ox28ccec,*ps = 2
access two elements with array notation
stacks[0] = 3, stacks[1] = 2
access two elements with pointer notation
*stacks = 3, *(stacks+1) = 2
在多数情况下,C++将数组名解释为数组第1个元素的地址。因此,下面的语句将pw声名为指向double类型的指针,然后将它初始化为wages数组中的第1个元素的地址:
double * pw = wages;
和所有数组一样,wages也存在下面的等式:
wages = &wages[0] = address of first element of array
接下来,程序查看pw和 ∗ * ∗pw的值,前者是地址,后者是存储在该地址中的值。由于pw指向第1个元素,因此 ∗ *