[英]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 ++来说更合适。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.