数组指针和指针数组实例辨析

#include <iostream>
using namespace std;

int main()
{
    int a[5] = { 1,3,5,7,9 };
    int b[4][3] = { { 1,2,3 },{ 4,5,6 },{ 7,8,9 },{ 10,11,12 } };

    int *pa = a;
    cout << &a << endl;
    cout << pa << endl;
    cout << &pa << endl;
    cout << *(pa+2) << endl;    //结果为5
    cout << pa[2] << endl;      //结果为5
    cout << "*************************************************************" << endl;

    int (*pc)[5] = &a;          //数组指针,pc是一个指针,它指向一个数组,pc里存储的是数组的地址
    cout << sizeof(pc) << endl; //结果为4
    cout << sizeof(*pc) << endl;//结果为4*5=20
    //int (*pc)[5] = a;         //错误,&a是整个数组的首地址而a是数组首元素的首地址
    //int (*pc)[5] = (int (*)[5])a;//正确,强制转换
    cout << **pc << endl;       //结果为a[0]=1
    cout << (*pc)[0] << endl;   //结果为a[0]=1
    cout << pc[0][0] << endl;   //结果为a[0]=1
    cout << *(*pc+2) << endl;   //结果为a[2]=5
    cout << (*pc)[2] << endl;   //结果为a[2]=5
    cout << pc[0][2] << endl;   //结果为a[2]=5
    cout << "*************************************************************" << endl;

    int (*pb)[3] = b; 
    cout << **pb << endl;       //结果为b[0][0]=1
    cout << (*pb)[0] << endl;   //结果为b[0][0]=1
    cout << pb[0][0] << endl;   //结果为b[0][0]=1
    cout << pb[2][1] << endl;   //结果为b[2][1]=8
    cout << *(pb[2]+1) << endl; //结果为b[2][1]=8
    cout << *(*(pb+2)+1) << endl; //结果为b[2][1]=8
    cout << *(*pb + 7) << endl;   //结果为b[2][1]=8
    cout << "*************************************************************" << endl;

    char *pd[6] = { "abc","lmn","opq","rst","uvw","xyz" };//指针数组,元素为指针的数组
    cout << *pd << endl;         //结果为abc
    cout << pd[0] << endl;       //结果为abc
    cout << pd[5] << endl;       //结果为xyz
    cout << *(pd+5) << endl;     //结果为xyz
    cout << pd[5][1] << endl;    //结果为y
    cout << *(pd[5]+1) << endl;  //结果为y
    cout << *(*(pd+5)+1)<< endl; //结果为y

    cin.get();
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值