指针与数组的关系

指针与数组的关系

#include <iostream>

int main()
{
    using namespace std;
    double wages[3] = {10000.0, 20000.0, 30000.0};
    short stacks[30] = {3, 2, 1};

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

    cout << "pw = " << pw << ", *pw = " << *pw << endl;
    pw += 1;
    cout << "add 1 to the pw pointer:\n";
    cout << "pw = " << pw << ", *pw = " << *pw << "\n\n";
    cout << "ps = " << ps << ", *ps = " << *ps << endl;
    ps = ps + 1;
    cout << "add 1 to the ps pointer:\n";
    cout << "ps = " << ps << ", *ps = " << *ps << "\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 << "*stack = " << *stacks << ", *(stack+1) = " << *(stacks+1) << endl;
    cout << sizeof(wages) << " = size of wages array\n";
    cout << sizeof(pw) << " = size of pw pointer\n";
    return 0;
}

对于数组表达式stacks[1],c++编译器将该表达式看作是*(stacks + 1),这意味着先计算数组第2个元素的地址,然后找到存储在那里的值。最后的结果便是stacs[1]的含义。

由程序的输出可知,*(stacks + 1)和stacks[1]是等价的,同样,*(stacks + 2)和stacks[2]适等价的,通常,使用数组表示法时,c++都执行转换:

arrayname[i] becomes * (arrayname + 1)

同时,如果使用的是指针,而不是数组名,则c++也将执行同样的转换:

pointername[i] becomes *(pointername + i)

所以在很多情况下,可以以相同的方式使用指针名和数组名。对于他们,可以使用数组方括号表示法,也可以使用解除引用运算符(*)。在多数表达中,他们都表示地址。

指针与数组的区别是:

可以修改指针的值,而数组名是常量:

pointername = pointername + 1 // valid 指针

arryname = arrayname + 1 // not allow 数组 该结果为arrayname[0] +=1

此外,对数组应用sizeof()运算符得到的数组的长度,而对指针应用sizeof得到的是指针的长度,即使指针指向的一个数组,例如,在以上程序中,pw和wages指的是同一个数组,但对他们应用sizeof运算符得到的结果如下:

24 = size of wages array << displaying sizeof wages
4 = size of pw pointer << displaying sizeof pw

这种情况下,c++不会将数组解释为地址。

数组的地址

数组名被解释为其第一个元素的地址,,而对数组名应用地址运算符时,得到的是整个数组的地址:

short tell[10];
cout << tell << endl;    // 输出&tell[0]
cout << &tell << endl;    // 输出全部数组的地址

从数字上说,这两个地址相同;但从概念上说,&tell[0](即tell)是一个2字节内存块的地址,而&tell时一个20字节内存块的地址。因此,表示tell+1将地址值加2,而表达式&tell+1将地址加20。tell是个short指针(short*)。而&tell是指向包含10个元素的short的数组(short(*)[10])

对于&tell的类型描述:

先来这么声明与初始化指针:

short (*pas)[10] = &tell;

如果省略括号,优先级规则将使得pas先与[10]结合,导致pas是一个short指针数组,它包含10个元素因此括号是必不可少的。其次,如果要描述变量的类型,,可将声明中的变量名删除。因此pas的类型为short(*)[10].另外由于pas被设置为&tell,因此,*pas与tell等价,所以(*pas)[0]为tell数组的一个元素。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值