Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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?

like image 590
StackUser Avatar asked Jun 05 '18 12:06

StackUser


Video Answer


2 Answers

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] = { ... };.

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.

like image 65
songyuanyao Avatar answered Sep 27 '22 19:09

songyuanyao


For such a request you can use the magic tool cdecl (also available as a web UI here):

$ cdecl -+ %c++ mode Type `help' or `?' for help cdecl> declare x as array of const pointer to char char * const x[] cdecl>  
like image 35
Jean-Baptiste Yunès Avatar answered Sep 27 '22 19:09

Jean-Baptiste Yunès