指向多维数组的第n个元素的指针

时间:2018-06-25 18:23:18

标签: c++ arrays pointers

我想知道如何使用指向该数组的指针访问多维数组的第n个元素。

假设我有以下内容

struct Struct_B
{
    bool asdf;
};

struct Struct_A
{
    int X;
    int Y;
    Struct_B *ptr;
};

typedef Struct_A new_typedef[10][20][30];

new_typedef Array;

// Set values within Array, including correctly setting ptr variable

// Within debugger, Array_ptr contains the correct data, identical to Array, as it should.
new_typedef* Array_ptr = &Array;

for ( int i = 0; i < 10; i++) {
    for ( int j = 0; j < 20; j++) {
        for (int k = 0; k < 30; k++) {
            // Crashes on this conditional'
            // Within debugger, asdf is in some random location in memory, implying I am not accessing it correctly.
            // Same problem exists if I attempt to access X or Y
            if ( (*Array_ptr)[i][j][k].ptr->asdf) {
                // Do stuff
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您必须首先取消引用指针:

(*Array_ptr)[i][j][k].X = 5;

编辑:

  

if ( (*Array_ptr)[i][j][k].ptr->asdf)崩溃

这是因为.ptr未初始化。