【原创】一起学C++ 之指针、数组、指针算术 ---------C++ primer plus(第6版)

时间:2023-03-09 04:32:39
【原创】一起学C++  之指针、数组、指针算术   ---------C++ primer plus(第6版)

C++ Primer Plus 第6版

指针和数组基本等价的原因在于指针算术!


一、指针

⑴整数变量+1后,其值将增加1;

⑵指针变量+1后,增加的量等于它指向的类型的字节数;

⑶C++将数组名解析为地址;

例如:如果系统对double使用8个字节存储,其数值将增加8,

     如果系统对short使用2个字节存储,则指针值将增加2

#include <iostream>
int main()
{
using namespace std;
double wages[]={10000.0,20000.0,30000.0};
short stacks[]={,,};
double *pw=wages; // 将 pw 声明为指向 double类型的指针,然后将它初始化为wages----wages数组中的第一个元素的地址
  
short *ps=&stacks[]; int a;//-----仅为保持dos界面
cout<<"pw= "<<pw<<", *pw ="<<*pw<<endl;
pw=pw+;
cout<<"add 1to the pw pointer:\n";
cout<<"pw= "<<pw<<", *pw = "<<*pw<<"\n\n";
cout<<"ps= "<<ps<<", *ps = "<<*ps<<endl;
ps=ps+;                       //指针+1 等价于 *(stacks+1)
cout<<"add 1 to the ps pointer:\n";
cout<<"ps ="<<ps<<", *ps = "<<*ps<<endl;
cout<<"access two elements with array notation\n";
cout<<"stack[0]= "<<stacks[]
<<", stack[1] ="<<stacks[]<<endl;
cout<<"access two elements with pointer notation\n";
cout<<"*stacks = "<<*stacks
<<", *(stacks+1) ="<<*(stacks+)<<endl; cout<<sizeof(wages)<<" = size of wages array\n";
cout<<sizeof(pw)<<" size of pw pointer\n";
cin>>a;//-----仅为保持dos界面 return ;
 }

【原创】一起学C++  之指针、数组、指针算术   ---------C++ primer plus(第6版)

解释上述代码:

1、在多数情况下,C++将数组名解释为数组第一个元素的地址;

  和所有数组一样wages也存在下面的等式:

   wages = &wages[0] =address of first element of array

  除了首地址可以这么简写,其他的都必须为 “&+变量名+索引[]”

2、stacks[1] 和 *(stacks +1) 是等价的:可以这么理解,stacks是数组名的第一个元素地址,stacks=&stacks[0]--->(stacks+1)=&stacks[0+1]

  所以 *(stacks +1)  等价于 stacks[1]

     *(stacks +2)  等价于 stacks[2]

结论:

  ① 使用数组表示法时:

    arrayname[i](数组名) 等价于 *( arrayname + i )

  ② 使用指针表示法时:

    pointername[i](指针名称) 等价于 *( pointername + i)

  ③2者使用时区别

    pointername=pointername+1;  //正确的

    arrayname=arrayname+1;      //不正确的


下面这个例子是:地址偏移,和地址对应的数值

  double wages[]={10000.0,20000.0,30000.0};
  double *pw=wages;
  double *pw1=&wages[];
  cout<<"pw= "<<pw<<", *pw ="<<*pw<<endl;
  cout<<"pw= "<<pw1<<", *pw ="<<*pw1<<endl;
  pw=pw+;
  cout<<"add 1to the pw pointer:\n";
  cout<<"pw= "<<pw<<", *pw = "<<*pw<<"\n\n";

【原创】一起学C++  之指针、数组、指针算术   ---------C++ primer plus(第6版)

二、数组

1、静态联编(静态数组)

使用数组声明来创建数组时,将采用静态联编,即数组的长度在编译时设置:

int tacos[];//static binding,size fixed at complie time

2、动态联编(动态数组)

使用 new[]来创建数组时,将采用动态联编(动态数组),即将在运行时维数组分配空间,其长度也将在运行时设置。使用完这种数组后,应使用delete[]来释放其占用的内存:

int size;
cin>>size;
int * pz=new int [size];  //dynamic binding,size set at run time
...
delete [] pz;         //free memony when finished

三、指针算术

C++允许将指针和整数相加。加1的结果等于原来的地址值加上指向的对象占用的总字节数。

仅当2个指针指向同一个数组时,这种运算才有意义:这将得到2各元素的间隔。

int tacos[]={,,,,,,,,,};
int * pt =tacos;
pt= pt + ;
int * pe=&tacos[];
pe=pe - ;
int diff=pe-pt; // 结果:7