股票

数组与指针的关系问题

    来源《C++ Primer Plus 5th》
    程序清单:addpntrs.cpp

  1. /* 
  2.  *  C++ Primer Plus 5th, Page 98 
  3.  *  addpntrs.cpp — pointer addition 
  4.  */  
  5. #include <iostream>  
  6. int main()  
  7. {  
  8.         using namespace std;  
  9.         double  wages[3]        =   {  10000 .0,  20000 .0,  30000 .0  };  
  10.         short   stacks[3]       =   {  3,  2,  1  };  
  11. /* Here are two ways to get the address of an array */  
  12.         double      *pw     =  wages;               /* name of an array = address */  
  13.         short       *ps     =   & stacks[0];        /* or use address operator */  
  14. /* with array element */  
  15.             cout  <<   “pw = “  <<  pw  <<   “, *pw = “  <<  *pw  <<  endl;  
  16.         pw  =  pw  +  1;  
  17.         cout  <<   “add 1 to the pw pointer:n”;  
  18.         cout  <<   “pw = “  <<  pw  <<   “, *pw = “  <<   * pw  <<   “nn”;  
  19.         cout  <<   “ps = “  <<  ps  <<   “, *ps = “  <<   * ps  <<  endl;  
  20.         ps  =  ps  +  1;  
  21.         cout  <<   “add 1 to the ps pointer:n”;  
  22.         cout  <<   “ps= “  <<  ps  <<   “, *ps = “  <<   * ps  <<   “nn”;  
  23.         cout  <<   “access two elements with array notationn”;  
  24.         cout     <<   “stacks[0] = “  <<  stacks[0]  
  25.              <<   “, stacks[1] “  <<  stacks[0]   <<  endl;  
  26.         cout  <<   “access two elements with pointer notationn”;  
  27.         cout     <<   “*stacks = “  <<   * stacks  
  28.              <<   “, *(stacks + 1) = “  <<   * (stacks  +  1)  <<  endl;  
  29.         cout  <<  sizeof( wages )   <<   ” = size of wages arrayn”;  
  30.         cout  <<  sizeof( pw )   <<   ” = size of pw pointern”;  
  31.         return( 0 );  
  32. }  

程序说明:
在大多数情况下,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)

打赏
原文链接:,转发请注明来源!

发表评论