【发布时间】:2020-04-20 05:14:37
【问题描述】:
对于许多 LEN,我在 [0,LEN) 中有许多整数的所有可能排列的常量二维数组:
static const char permu2[][2] = {{0, 1}, {1, 0}};
static const char permu3[][3] = {{0, 1, 2}, {0, 2, 1}, {1, 0, 2},
{1, 2, 0}, {2, 0, 1}, {2, 1, 0}};
static const char permu4[][4] = {
{0, 1, 2, 3}, {0, 1, 3, 2}, {0, 2, 1, 3}, {0, 2, 3, 1}, {0, 3, 1, 2},
{0, 3, 2, 1}, {1, 0, 2, 3}, {1, 0, 3, 2}, {1, 2, 0, 3}, {1, 2, 3, 0},
{1, 3, 0, 2}, {1, 3, 2, 0}, {2, 0, 1, 3}, {2, 0, 3, 1}, {2, 1, 0, 3},
{2, 1, 3, 0}, {2, 3, 0, 1}, {2, 3, 1, 0}, {3, 0, 1, 2}, {3, 0, 2, 1},
{3, 1, 0, 2}, {3, 1, 2, 0}, {3, 2, 0, 1}, {3, 2, 1, 0}};
static const char permu5[][5] = {{0, 1, 2, 3, 4}, {0, 1, 2, 4, 3}, {0, 1, 3, 2, 4}, /*... */}
// and many more as you can imagine...
我想将指向这些数组的指针存储在另一个数组中:
static const char *permu[] = {0, 0, permu2, permu3, permu4,
permu5, permu6, permu7, permu8};
static const int fac_seq[] = {1, 1, 2, 6, 24, 120,
720, 5040, 40320, 362880, 3628800, 39916800};
因此对于给定的 LEN=n,我可以通过这种方式访问这些常量:
const int n = 8;
for ( size_t i = 0; i < fac_seq[n]; i++ ) {
for ( size_t j = 0; j < n; j++ ) {
printf( "%2d", *( permu[n] + n*i + j ) );
}
putchar( '\n' );
}
虽然这将编译并正常工作,但编译器 (gcc) 抱怨如下:
30.c:1966:47: warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]
static const char *permu[] = {0, 0, permu2, permu3, permu4,
^~~~~~
30.c:1966:47: note: (near initialization for ‘permu[2]’)
30.c:1966:55: warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]
static const char *permu[] = {0, 0, permu2, permu3, permu4,
^~~~~~
30.c:1966:55: note: (near initialization for ‘permu[3]’)
permu 数组的正确类型应该是什么?我试过const char **permu[] 仍然收到同样的警告。
【问题讨论】:
-
你可以试试
static const void *permu[]?然后,您必须在访问时强制转换它。或者,您可以将每个数组设为一维并自己计算索引。 -
@WeatherVane 是的,这行得通,谢谢!只要让它成为一个答案,我会接受它:)