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

Sta*_*ser 21 c++ arrays pointers const c++11

有没有办法定义一个指针数组,以便任何指针是const?

例如,可以char** array定义array[0]为const和array[1]const等,但是array非const并且array[j][i]是非const?

son*_*yao 21

char* const * pointer;.然后

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
Run Code Online (Sandbox Code Playgroud)

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

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

int n = ...;
char* const * pointer = new char* const [n] { ... };
...
delete[] pointer;
Run Code Online (Sandbox Code Playgroud)

如您所见,您必须手动执行分配和释放.即使你已经说过你不想要,std::vector但对于现代C++使用std::vector智能指针更合适.

  • @StackUser然后你必须使用指针和`new []`.例如`char*const*pointer = new char*const [42] {...};`.最后,即使你已经说过你不想要`std :: vecto`:但对于使用`std :: vector`的现代C++来说更合适. (3认同)
  • @StackUser它是数组的大小,它包含42个元素. (2认同)
  • @StackUser是的. (2认同)

Jea*_*nès 14

对于这样的请求,您可以使用魔术工具cdecl(此处也可用作Web UI ):

$ cdecl -+ %c++ mode
Type `help' or `?' for help
cdecl> declare x as array of const pointer to char
char * const x[]
cdecl> 
Run Code Online (Sandbox Code Playgroud)