c++ - 如何在 C++ 中定义一个 const 指针数组?

标签 c++ arrays c++11 pointers constants

有没有办法定义一个指针数组,使任何指针都是 const 的?

例如,是否可以将 char** 数组 定义为 array[0] 为 const 而 array[1] 为 const,等等,但是 array 是非常量并且 array[j][i] 是非常量?

最佳答案

char* const * 指针;。那么

pointer       -> non-const pointer to const pointer to non-const char (char* const *)
pointer[0]    -> const pointer to non-const char (char* const)
pointer[0][0] -> non-const char

如果你想要一个数组,那么 char* const array[42] = { ... };.

如果你在编译时不知道数组的大小并且必须在运行时分配数组,你可以使用指针然后

int n = ...;
char* const * pointer = new char* const [n] { ... };
...
delete[] pointer;

如您所见,您必须手动执行分配和解除分配。即使你已经说过你不想要 std::vector 但对于使用 std::vector 的现代 C++或 smart pointers比较合适。

关于c++ - 如何在 C++ 中定义一个 const 指针数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50700470/

相关文章:

c++ - Visual Studio13 创建线程和优化流程

c++ - 有没有办法在同一项目的另一个 .cpp 中使用 .cpp 中声明的静态 void

c++ - 我的 Qt 代码不能用 "cannot call member function without object"编译

c++ - 在 C 或 C++ 中用 1 到 10^10 的随机数填充数组

c++ - 编译时循环遍历模板化类型

c++ - 通过模板参数给定其长度,在编译时生成相同类型的 std::tuple

arrays - “下一步”按钮在我的 Swift 测验应用程序中不起作用

arrays - Powershell 比较数组元素

c++ - 在 std::function 中调用递归函数

c++ - 在 OS X 上轮询和选择奇怪的行为