const数组指向const值的指针

时间:2012-08-07 17:13:41

标签: c++ arrays const const-correctness

如果我创建一个const值的全局数组,例如

const int SOME_LIST[SOME_LIST_SIZE] = {2, 3, 5, 7, 11};

是否可以以任何方式修改SOME_LIST?

如何编写这样的SOME_LIST指向const内存位置,并且是一个const指针本身(即不能指向其他地方)?

2 个答案:

答案 0 :(得分:12)

有三个主要的指针示例涉及“const”关键字。 (见link

首先:声明一个指向常量变量的指针。指针可以移动,并改变它指向的内容,但不能修改变量。

const int* p_int;

其次:声明一个指向变量的“不可移动”指针。指针是“固定的”,但数据可以修改。必须声明并指定此指针,否则它可能指向NULL,并在那里得到修复。

int my_int = 100;
int* const constant_p_int = &my_int;

第三:声明一个指向常量数据的不可移动指针。

const int my_constant_int = 100; (OR "int const my_constant_int = 100;")
const int* const constant_p_int = &my_constant_int;

你也可以使用它。

int const * const constant_p_int = &my_constant_int;

另一个好的参考资料见here。我希望这会有所帮助,虽然写这篇文章时我发现你的问题已经得到了解答......

答案 1 :(得分:10)

你拥有它的方式是正确的。

此外,您无需提供SOME_LIST_SIZE; C ++会自动从初始化器中找出它。

相关问题