【问题标题】:what is the meaning of [3] in int(*p)[3]?int(*p)[3]中的[3]是什么意思?
【发布时间】:2019-10-18 04:08:11
【问题描述】:

我正在研究 C++ 中的数组和指针。
在这段代码中,我无法理解 'int (*c)[3] = a' 中 [3] 的含义。
是来自'int a[2][3]'?? 但是有两个数字,2 和 3。
为什么我们不使用 [2]?
请告诉我 (*c) 旁边的数字规则。

 #include <iostream>

    using namespace std;

    int main()
    {
        int a[2][3] = {{0,1,2}, {3,4,5}};

        cout << "\n";

        int (*c)[3] = a; // type of a and c: int (*)[3]
        cout << "c + 1 = " << c + 1 << "\n";
        cout << "\n";
        cout << "Distance between c + 1 and a: " <<
            reinterpret_cast<uintptr_t>(c+1) - reinterpret_cast<uintptr_t>(a) 
        << "\n";


        return 0;
    }

【问题讨论】:

    标签: arrays pointers


    【解决方案1】:

    a是一个二维数组,2组3个整数。

    c 是一个指向 3 个整数的一维数组的指针。 在 c 的声明中,[3] 定义了 c 的大小。

    由于 c 是一个指针,设置 c = ac 指向 中的第一个三元组>a (c[0]=>a[0][0], c[1]=>a[0][1], c[2]=>a[0][2])

    当我们递增时,c 上的 [3] 变得很重要:c + 1 实际上是 a[1],第二个三元组一个c 指针增加了 c 的大小,即 int[3]。

    一清二楚? :-)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-08
      • 2013-08-14
      • 2017-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多