简体   繁体   English

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

[英]How to define an array of const pointers in C++?

Is there a way to define an array of pointers so that any pointer is const? 有没有办法定义一个指针数组,以便任何指针是const?

For example, can a char** array be defined so array[0] is const and array[1] is const, etc., but array is non-const and array[j][i] is non-const? 例如,可以定义char** array因此array[0]是const而array[1]是const等,但是array是非const而array[j][i]是非const?

char* const * pointer; . then 然后

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

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

If you don't know the size of array at compile-time and have to allocate the array at run-time, you could use the pointer then 如果在编译时不知道数组的大小并且必须在运行时分配数组,那么可以使用指针然后

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

As you can see, you have to perform allocation and deallocation manually. 如您所见,您必须手动执行分配和释放。 Even you've said you don't want std::vector but for mordern C++ using std::vector or smart pointers is more appropriate. 即使你已经说过你不想要std::vector但是对于使用std::vector智能指针的现代C ++来说更合适。

For such a request you can use the magic tool cdecl (also available as a web UI here ): 对于这样的请求,您可以使用魔术工具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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM