Reputation: 571
I have this global enum and a 3D array:
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}}
};
and I need a pointer (or possibly a copy) which points to a particular 2D sub-array of placeRecipeIndexes
which means that by pointing to placeRecipeIndexes[0]
, I would have a 2D array looking like this:
{{0, EMPTY}, {1, EMPTY}, {EMPTY, EMPTY}}
.
At first, I tried it without a pointer: const int indexes[_PHASE_COUNT][TOOLS_REPEAT_COUNT] = toolsIndexes[idx];
but it gave me:
Array initializer must be an initializer list.
so I tried to do it like this:
const int **indexes = (const int **) toolsIndexes[idx];
but I can't access the indexes
array positions because they're presumably empty - I'm getting SIGSEV
.
I thought that this should definitely work. Am I missing something important here?
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;
}
Upvotes: 2
Views: 46
Reputation: 17648
Replace:
const int **indexes = (const int **) placeRecipeIndexes[0];
with:
const int (*indexes)[2] = placeRecipeIndexes[0]; // C
or:
const int (&indexes)[3][2] = placeRecipeIndexes[0]; // C++
For verification, the following check out (in C++):
static_assert(&indexes[0][0] == &placeRecipeIndexes[0][0][0]);
static_assert(&indexes[2][1] == &placeRecipeIndexes[0][2][1]);
Upvotes: 1