当前位置:   article > 正文

C++:指针数组与多级指针_c++ 指针指向的数组的元素个数

c++ 指针指向的数组的元素个数

指针数组的定义:

int main() {
   
    //定义数组  数据类型  数据名[元素个数] = {值1,值2}
    //定义指针数组
    int a = 10;
    int b = 20;
    int c = 30;
    int* arr[3] = { &a,&b,&c };
    cout << *arr[0] << endl;//结果为10
    for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {
        cout << *arr[i] << endl;//打印a,b,c
    }
    cout << "指针数组大小:" << sizeof(arr) << endl;
    cout << "指针元素大小:" << sizeof(arr[0]) << endl;
   
   
    system("pause");
    return 0;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

在这里插入图片描述


int main() {
   
    //指针数组中的元素是指针
    int a[] = { 1,2,3 };
    int b[] = { 4,5,6 };
    int c[] = { 7,8,9 };
    //指针数组是一个特殊的二维数组模型
    //指针数组对应于二级指针
    int* arr[] = { a,b,c };//数组名即指向数组首元素的指针
    int** p = arr;

    cout << arr[0][1] << endl;//arr[0]是首地址,看做一个整体,接下来[1]就相当于数组的用法
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            //二维数组方式打印
            //cout << arr[i][j] << endl;

            //偏移量打印
           // cout << *(arr[i] + j);

            cout << *(*(arr + i) + j);


        }
        cout << endl;
    }
   
   
    system("pause");
    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

多级指针

//指针数组中的元素是指针
    int a[] = { 1,2,3 };
    int b[] = { 4,5,6 };
    int c[] = { 7,8,9 };
  
    int* arr[] = { a,b,c };
    int** p = arr;

    cout << **p << endl;//结果为1
    
    cout << *(*p + 1) << endl;//结果为2
    cout << **(p + 1) << endl;//结果为4
    cout << *(*(p + 1) + 1) << endl;//结果为5

    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            //cout << p[i][j];
            //cout << *(p[i] + j);
            //cout << *(*(p + i) + j);
            
        }
        cout << endl;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

在这里插入图片描述


int main() {
    int a = 10;
    int b = 20;

    int* p = &a;
    int** pp = &p;

    //*pp = &b;//等价于p=&b
    cout << *p << endl;//20
    system("pause");
    return 0;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/223595
推荐阅读
相关标签
  

闽ICP备14008679号