C++

关于指针数组和指向数组的指针

2017-03-18  本文已影响0人  codinRay

关于int *p[SIZE] 和 int (*p)[SIZE]的问题,也就是<strong>指针数组</strong>和<strong>指向数组的指针</strong>的问题,首先要明确一点 :

<strong>[]运算符的优先级大于*</strong>

某天刷知乎的时候刚好看到这个,有人说
对于前者,官方支持的写法是

<strong>int *(p[SIZE])</strong>

这种写法显然更能帮助人理解指针数组和指向数组的指针的区别。

#include <iostream>
using namespace std;
int main(void)
{
    ios::sync_with_stdio(false);
    cin.tie(false);

    int arr[5] = { 1,2,3,4,5 };

    int *(pt[5]); // 能存放5个元素的指针数组

    int(*Parr)[5]; // 指向能存放5个元素的数组的指针

    // 遍历指针数组
    for (int i = 0; i < 5; i++) {
        int *curP = &arr[i];
        pt[i] = curP;
        cout << *(pt[i]) << ' ';
    }
    
    cout << endl;

    // 利用数组指针遍历数组 (【强转】的使用)
    Parr = &arr;
    for (int i = 0; i < 5; Parr = (int(*)[5])((int *)Parr + 1), i++) {
        cout << *(*Parr) << ' ';
    }
    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读