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

Pointer to nth element of multi-dimensional array

本文关键字:元素 指针 数组      更新时间:2023-10-16

我想知道如何使用指向该数组的指针访问该数组的第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
}
}
}
}

您必须先取消引用指针:

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

编辑:

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

那是因为.ptr是未初始化的。