在C ++中陈述常量数组值

时间:2011-04-07 13:44:27

标签: c++ arrays const

例如我有:

int boo[8];
boo[1] = boo[3] = boo[7] = 4;
boo[0] = boo[2] = 7;
boo[4] = boo[5] = boo[6] = 15;

我应该如何输入常量值?我看到了类似的问题,但它没有帮助我。

编辑: 还有一个问题,如果指数为0 1 3 4 5 6 7的boo是不变的,但boo [2]不是?是可以做到的吗?

2 个答案:

答案 0 :(得分:7)

这是你在找什么?

const int boo[] = { 7, 4, 7, 4, 15, 15, 15, 4 };

获取一个非const指针,指向数组中的一个条目,如下所示:

int * foo = (int*)&boo[2];

答案 1 :(得分:3)

一个不那么优雅的解决方案可能是:

const int boo[8] = {7,4,7,4,15,15,15,4};

另一种解决方案可能是:

int boo_[8];
boo_[1] = boo_[3] = boo_[7] = 4;
boo_[0] = boo_[2] = 7;
boo_[4] = boo_[5] = boo_[6] = 15;
const int * boo = boo_;