来源《C++ Primer Plus 5th》
程序清单:addpntrs.cpp
- /*
- * C++ Primer Plus 5th, Page 98
- * addpntrs.cpp — pointer addition
- */
- #include <iostream>
- int main()
- {
- using namespace std;
- double wages[3] = { 10000 .0, 20000 .0, 30000 .0 };
- short stacks[3] = { 3, 2, 1 };
- /* Here are two ways to get the address of an array */
- double *pw = wages; /* name of an array = address */
- short *ps = & stacks[0]; /* or use address operator */
- /* with array element */
- cout << “pw = “ << pw << “, *pw = “ << *pw << endl;
- pw = pw + 1;
- cout << “add 1 to the pw pointer:n”;
- cout << “pw = “ << pw << “, *pw = “ << * pw << “nn”;
- cout << “ps = “ << ps << “, *ps = “ << * ps << endl;
- ps = ps + 1;
- cout << “add 1 to the ps pointer:n”;
- cout << “ps= “ << ps << “, *ps = “ << * ps << “nn”;
- cout << “access two elements with array notationn”;
- cout << “stacks[0] = “ << stacks[0]
- << “, stacks[1] “ << stacks[0] << endl;
- cout << “access two elements with pointer notationn”;
- cout << “*stacks = “ << * stacks
- << “, *(stacks + 1) = “ << * (stacks + 1) << endl;
- cout << sizeof( wages ) << ” = size of wages arrayn”;
- cout << sizeof( pw ) << ” = size of pw pointern”;
- return( 0 );
- }
程序说明:
在大多数情况下,C++将数组名解释为数组第1个元素的地址。
double *pw=wages;
将pw声明为指向double类型的指针,然后将它初始化为wages–wages数组中第1个元素的地址。
wages存在下面的等式:
wages = &wages[0] = address of first element of array
通常,使用数组表示法时,C++都执行下面的转换:
arrayname[i] becomes *(arrayname+i)
如果使用的是指针,而不是数组名,则C++也执行同样的转换:
pointername[i] becomes *(pointername+i)