convertion form char** to const char** error

M

mihai

Hi,

I have a question regarding the conversion (in c or c++) from char**
to const char**.

The fallowing code refuses :) to compile with g++ (and others):

char **p;
const char **q = static_cast<const char**>(p);

or, exact the same situation:

void f(const char **p) {}
int main() {
f(p);
return 0;
}

And I don't understand why. It should work because is a conversion for
a non const pointer to a const pointer.

Thank you,
Mihai.
 
J

Juha Nieminen

mihai said:
char **p;
const char **q = static_cast<const char**>(p);

Rather ironically const_cast will work. (It's ironic because
const_cast is usually used to *remove* constness, not to add it.)
 
J

James Kanze

I have a question regarding the conversion (in c or c++) from
char** to const char**.
The fallowing code refuses :) to compile with g++ (and others):
char **p;
const char **q = static_cast<const char**>(p);
or, exact the same situation:
void f(const char **p) {}
int main() {
f(p);
return 0;
}
And I don't understand why. It should work because is a
conversion for a non const pointer to a const pointer.

No it's not. It's a conversion between two different types of
non-const pointers. Allowing it would break const:

char* p ;
char** pp = &p ;
char const** pcp = pp ;
char const* pc = "doh!" ;
*pcp = pc ;
*p = '\0' ;

Thus, it's forbidden.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,262
Messages
2,571,052
Members
48,769
Latest member
Clifft

Latest Threads

Top