指针、数组和指针加减

指针、数组和指针算数

指针和数组基本等价的原因在于指针算数c++内部处理数组的方式。指针变量加1,增加的量等于它指向的类型的字节数。将指向double的指针加1后,如果系统对double使用8字节存储,则数值增加8字节。
下面的例子展示了指针、数组和指针算数。指针和指针都可以通过指针和数组的方式获取数组的值。

#include <iostream>

int main()
{
    using namespace std;
    double wages[] = { 10000,20000,30000 };
    short stacks[] = { 3,2,1 };

    double* pw = wages;
    short* ps = &stacks[0];

    cout << "pw = " << pw << ", *pw = " << *pw << endl;
    pw = pw + 1;
    cout << "pw + 1   " << endl;
    cout << "pw = " << pw << ", *pw = " << *pw << "\n\n";

    cout << "ps = " << ps << ", *ps = " << *ps << endl;
    ps = ps + 1;
    cout << "ps + 1   " << endl;
    cout << "ps = " << ps << ", *ps = " << *ps << "\n\n";

    cout << "access elements with array notation\n";
    cout << "stacks[0]= " << stacks[0] <<", stacks[1]= "<<stacks[1] << "\n\n";

    cout << "access elements with pointer notation\n";
    cout << "*stacks= " << *stacks << ", *(stacks+1)= " << *(stacks + 1) << "\n\n";

    cout << sizeof(stacks) << " size of stacks\n";
    cout << sizeof(ps) << " size of ps\n\n";

    ps--;
    cout << "ps[0]= " << ps[0] << ", ps[1]=" << ps[1] << ", ps[2]=" << ps[2] << "\n";
    cout << "*ps= " << *ps << ", *(ps+1)=" << *(ps+1) << ", *(ps+2)=" << *(ps+2) << "\n";

    return 0;

}

输出

pw = 00DAFA28, *pw = 10000
pw + 1
pw = 00DAFA30, *pw = 20000

ps = 00DAFA18, *ps = 3
ps + 1
ps = 00DAFA1A, *ps = 2

access elements with array notation
stacks[0]= 3, stacks[1]= 2

access elements with pointer notation
*stacks= 3, *(stacks+1)= 2

6 size of stacks
4 size of ps

ps[0]= 3, ps[1]=2, ps[2]=1
*ps= 3, *(ps+1)=2, *(ps+2)=1

c++将数组名解释为地址。多数情况下c++将数组名解释为数组第一个元素的地址。 以下2种定义方式是等价的。

    double* pw = wages;
    short* ps = &stacks[0];

从输出可知,*(stacks+1), stacks[1], *(ps+1), ps[1]是等价的。通常使用数组表示法时,C++都会执行以下转换:

arrayname[i] becomes *(arrayname + 1)
如果使用的是指针,而不是数组名,c++也会执行相同的操作:
ptrname[i] becomes *(ptrname + 1)
因此,在多数情况下,可以用相同的方式使用数组名和指针名。对于他们,可以使用数组方括号表示法,也可以使用指针解除引用运算符(*)。

二者由2点不同:

  1. 可以修改指针的值,而数组名是常量
     ptrname = ptrname + 1;//valid
     arrayname = arrayname + 1;// not valid
    
  2. 对数组使用sizeof得到的是数组的长度,对指针使用得到的是指针的长度,即使指针指向的是一个数组。例如本例中对stacks数组和ps指针使用sizeof得到的结果:
6 size of stacks
4 size of ps
数组的地址
数组名被解释为数组第一个元素的地址,而对数组名应用地址运算符时,得到的是整个数组的地址。二者略有不同。
short tell[10];
cout<<tell<<endl;
cout<<&tell;

二者虽然在数值上是相同的;但是从概念上说,&tell[0](即tell)是一个2字节内存块的地址,而&tell是一个20字节的内存块的地址。因此,表达式tell+1将地址值加2,而&tell+1将地址值加20.

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值