我想用常量值初始化一个int数组,所有2 ^ n值从2 ^ 0到2 ^ 31我想知道下面哪个方法是正确的,如果它给出了我想要的结果,如果有的话更简单或更简短的方法来初始化它。
static const char two_n[32];
two_n[32] = {1, 2 ,4 ,8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096,
8192, 16384, 32768, 65535, 131070, 262140, 524280, 1048560,
2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728,
268435456, 536870912, 1073741824, 2147483648};
或
static const char *two_n[32];
two_n[32] = {1, 2 ,4 ,8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096,
8192, 16384, 32768, 65535, 131070, 262140, 524280, 1048560,
2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728,
268435456, 536870912, 1073741824, 2147483648};
或
static const int two_n[32];
two_n[32] = {1, 2 ,4 ,8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096,
8192, 16384, 32768, 65535, 131070, 262140, 524280, 1048560,
2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728,
268435456, 536870912, 1073741824, 2147483648};
答案 0 :(得分:3)
以上两种情况都不是因为数组和初始值设定项的类型都不正确。使用uint32_t
或unsigned long
,因为它们保证至少32位宽并且能够保持2 31 的值,这可能超出{{{ 1}}:
int