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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LYJ_viviani/article/details/62044705
#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;
}

猜你喜欢

转载自blog.csdn.net/LYJ_viviani/article/details/62044705