[英]How to define an array of const pointers in C++?
有沒有辦法定義一個指針數組,以便任何指針是const?
例如,可以定義char** array
因此array[0]
是const而array[1]
是const等,但是array
是非const而array[j][i]
是非const?
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
如果你想要一個數組,那么char* const array[42] = { ... };
。
如果在編譯時不知道數組的大小並且必須在運行時分配數組,那么可以使用指針然后
int n = ...;
char* const * pointer = new char* const [n] { ... };
...
delete[] pointer;
如您所見,您必須手動執行分配和釋放。 即使你已經說過你不想要std::vector
但是對於使用std::vector
或智能指針的現代C ++來說更合適。
對於這樣的請求,您可以使用魔術工具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.