Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a pointer to pointer to constant in C++?

Tags:

c++

pointers

I'm trying to write a function to parse command line arguments. This is the function declaration:

void parse(int, char const **);

Just in case, I have also tried (const char)**, const char **, and cchar ** using a typedef const char cchar. However, all of these (as expected, since they should all be identical) result in an error if I pass a char ** into the function, as in:

void main(int argc, char **argv) {
    parse(argc, argv);

The error I get from GNU's compiler is error: invalid conversion from 'char**' to 'const char**' and the one from Clang is candidate function not viable: no known conversion from 'char **' to 'const char **' for 2nd argument.

I have seen such solutions suggested as declaring a pointer to a const pointer to char (const char * const *), but I don't want either pointer to be const because I want to be able to modify the pointer so I can iterate over an argument using for(; **argv; ++*argv). How can I declare a "non-const pointer to non-const pointer to const char"?

like image 463
Dead Beetle Avatar asked Dec 06 '25 17:12

Dead Beetle


1 Answers

The function should be declared as:

void parse(int, char const * const *);

In C++, char ** can implicitly add const at all pointer depths, so you can call it as parse(argc, argv).

In C, const can only be added at the first pointer depth (this is a design defect in the language). Here is a dedicated thread. So you have to call the function as: parse(argc, (char const * const *)argv); unfortunately.

like image 101
M.M Avatar answered Dec 12 '25 04:12

M.M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!