c++ - 使用数组的指针间接寻址

标签 c++ arrays pointers dynamic indirection

我正在尝试使用一个指向二级间接寻址的附加指针来实现三个级别的指针间接寻址。这是为了上课,我遇到了一些实际问题。这就是我正在做的。

int ***s = new int **[row];
*s = new int *[row];
**s = new int[row];

现在如果这些只是 int 而不是我可以做的数组,

***s = 1;

要将它存储到我图片上的黄色方 block 中,但我不知道如何访问数组元素,我尝试了一些方法,它要么崩溃要么无法编译。任何帮助,甚至为我指明正确的方向都会非常有用。谢谢。

pointer diagram

最佳答案

你已经创建了这样的东西(假设 row 是 2 并输入 T):

                           T***
                          +-----+
                          |     |
                          +--/--+
                            /
                           / T**
                       +--/--+-----+
                       |     |     |
                       +-----+--+--+
                       -/       |
                    --/      T* |
                +--/--+-----+ +-+---+-----+
                |     |     | |     |     |
                +-----+-----+ +--+--+-----+
            ----/      -/        |      \---
      -----/        --/      T   |          \--
  +--/--+-----+ +--/--+-----+ +--+--+-----+ +--\--+-----+
  |     |     | |  X  |     | |     |     | |     |     |
  +-----+-----+ +-----+-----+ +-----+-----+ +-----+-----+

Every node would point to the next level's first node. Dereferencing every level would give the level next but you've to also take care of the index of the element in the array you want to reach. This, I see, isn't done in your code. For scalars you dereference using * while for arrays the array index syntax does dereferencing too apart from choosing the right element. * on arrays would just get you the first element always.

To access X in the above figure you'd do

T** v = u[0];
T* w = v[1];
T x = w[0];
// shorthand for above
x = u[0][1][0];

要在最后一层有一个数组,你应该这样做

int*** p = new int**;
*p = new int*;
**p = new int[row];

这只会给你 █ → █ → █ → █ █ █ …,其中 p 本身(第一个框)是一个自动变量(通常存储在堆栈空间中),其余来自freestore(通常位于堆中)。

Live example .

关于c++ - 使用数组的指针间接寻址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32430672/

相关文章:

java - 获取List的Arraylist中与Arraylist匹配的数据

c - 二维数组和指针

c++ - 在窗口未激活时获取输入 (Windows)

c++ - 在 QTCreator 中链接到 user32.lib

c++ - 数字输入的输入验证

c - 函数无法在 c 中正确打印

c++ - C++11 委托(delegate)的 ctors 是否比调用 init 函数的 C++03 ctors 表现更差?

javascript - 如何向对象数组添加新元素?

c++ - 指向成员函数语法的指针

c - 使用 char **,将 char ** 初始化为 C 中的字符串数组