const数组指向const值的指针

Cas*_*all 9 c++ arrays const const-correctness

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

const int SOME_LIST[SOME_LIST_SIZE] = {2, 3, 5, 7, 11};
Run Code Online (Sandbox Code Playgroud)

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

我怎么写这个SOME_LIST指向一个const内存位置,并且是一个const指针本身(即不能指向其他地方)?

use*_*501 13

有三个主要的指针示例涉及"const"关键字.(见此链接)

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

const int* p_int;
Run Code Online (Sandbox Code Playgroud)

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

int my_int = 100;
int* const constant_p_int = &my_int;
Run Code Online (Sandbox Code Playgroud)

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

const int my_constant_int = 100; (OR "int const my_constant_int = 100;")
const int* const constant_p_int = &my_constant_int;
Run Code Online (Sandbox Code Playgroud)

你也可以用这个.

int const * const constant_p_int = &my_constant_int;
Run Code Online (Sandbox Code Playgroud)

另一个很好的参考看到这里.我希望这会有所帮助,虽然在写这篇文章时我发现你的问题已经得到了回答......

  • 我熟悉const指针的使用,它只是我不确定的数组.仍然是非常好的事情要知道.:) (2认同)

KRy*_*yan 10

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

此外,您不需要提供SOME_LIST_SIZE; C++将从初始化程序中自动计算出来.

  • 当然:数组不能重新定位,`memset`会抱怨你给它一个`const`指针.显然你可以用`const_cast`绕过这个最后的保护,但是你进入UB-land(它可能会导致运行时崩溃). (3认同)
  • `const int SOME_LIST[]` 在传递给函数时衰减为 `const int *`。OP 是不是要求一种定义 `SOME_LIST[]` 的方法,使其衰减为 `const int * const`? (3认同)