c-将双int指针投射到规则的2D数组



我有这个全局枚举和一个3D数组:

enum place { SCISSORS, DRILL, BENDING_MACHINE, WELDER, PAINT_SHOP, SCREWDRIVER, MILLING_CUTTER };
const int placeRecipeIndexes[_PLACE_COUNT][_PHASE_COUNT][TOOLS_REPEAT_COUNT] = {
[SCISSORS] = {{0, EMPTY}, {1, EMPTY}, {EMPTY, EMPTY}},
[DRILL] = {{1, 4}, {0, 3}, {1, 3}},
[BENDING_MACHINE] = {{2, EMPTY}, {EMPTY, EMPTY}, {EMPTY, EMPTY}},
[WELDER] = {{3, EMPTY}, {EMPTY, EMPTY}, {EMPTY, EMPTY}},
[PAINT_SHOP] = {{5, EMPTY}, {4, EMPTY}, {5, EMPTY}},
[SCREWDRIVER] = {{EMPTY, EMPTY}, {5, EMPTY}, {2, EMPTY}},
[MILLING_CUTTER] = {{EMPTY, EMPTY}, {2, EMPTY}, {0, 4}}
};

我需要一个指针(或者可能是一个副本(,它指向placeRecipeIndexes的特定2D子阵列,这意味着通过指向placeRecipeIndexes[0],我将拥有一个如下所示的2D阵列:

{{0, EMPTY}, {1, EMPTY}, {EMPTY, EMPTY}}

起初,我在没有指针的情况下尝试了它:const int indexes[_PHASE_COUNT][TOOLS_REPEAT_COUNT] = toolsIndexes[idx];,但它给了我:

数组初始值设定项必须是初始值设定值列表

所以我试着这样做:

const int **indexes = (const int **) toolsIndexes[idx];

但我无法访问indexes数组位置,因为它们可能是空的——我得到的是SIGSEV

我认为这肯定会奏效。我是不是错过了什么重要的东西?

MRE:

#include <stdio.h>
#define EMPTY -1
enum place { SCISSORS, DRILL, BENDING_MACHINE, WELDER, PAINT_SHOP, SCREWDRIVER, MILLING_CUTTER };
const int placeRecipeIndexes[7][3][2] = {
[SCISSORS] = {{0, EMPTY}, {1, EMPTY}, {EMPTY, EMPTY}},
[DRILL] = {{1, 4}, {0, 3}, {1, 3}},
[BENDING_MACHINE] = {{2, EMPTY}, {EMPTY, EMPTY}, {EMPTY, EMPTY}},
[WELDER] = {{3, EMPTY}, {EMPTY, EMPTY}, {EMPTY, EMPTY}},
[PAINT_SHOP] = {{5, EMPTY}, {4, EMPTY}, {5, EMPTY}},
[SCREWDRIVER] = {{EMPTY, EMPTY}, {5, EMPTY}, {2, EMPTY}},
[MILLING_CUTTER] = {{EMPTY, EMPTY}, {2, EMPTY}, {0, 4}}
};
int main() {
const int **indexes = (const int **) placeRecipeIndexes[0];
printf("{");
for (int i = 0; i < 3; i++) {
printf("{%d, ", indexes[i][0]);
if (i != 2) {
printf("%d}, ", indexes[i][1]);
}
else {
printf("%d}", indexes[i][1]);
}
}
printf("}n");
// The output should be: {{0, -1}, {1, -1}, {-1, -1}}
return 0;
}

替换:

const int **indexes = (const int **) placeRecipeIndexes[0];

带有:

const int (*indexes)[2] = placeRecipeIndexes[0];     // C

或:

const int (&indexes)[3][2] = placeRecipeIndexes[0];  // C++

为了验证,以下检查(在C++中(:

static_assert(&indexes[0][0] == &placeRecipeIndexes[0][0][0]);
static_assert(&indexes[2][1] == &placeRecipeIndexes[0][2][1]);

最新更新