Why does this allow promotion from (char *) to (const char *)?

Given that scanf has (const char *) in the documentation from Microsoft and the answer to this question , what happens when I do the same to advance (char **) to (const char **)?

Basically, why is this compiling?

#include <stdio.h> int main(int argc, char **argv) { char szArray[50]; int i = 0; strcpy(szArray,"10"); /* the following code is upcasting the (char *) to (const char *) */ sscanf(szArray,"%d",&i); return 0; } 

And why doesn't this compile?

 #include <stdio.h> void processargs(const char **p) { } int main(int argc, char **argv) { processargs(argv); return 0; } 

Both seem to be doing the same with the pointer!

+4
source share
4 answers

char** -> const char ** is dangerous since you might accidentally modify the underlying const object.

The correct way to write what you want:

 void processargs(const char * const *p) { } 
+12
source

You are allowed to increase access restriction, you simply cannot reduce it. The transition from the regular pointer to the const pointer is excellent, the transition from the const pointer to the normal pointer is not performed.

The second example does not compile because you are not converting a pointer to a const pointer, you are converting it from a pointer to one type ( char* ) to another ( const char* ). For example, you can change char** to char* const* , but not to const char** .

+3
source

Check if this is explained to you:

 char * a_mutable = /*...*/; const char * a_constant = /*...*/; char **pointer_to_mutable = &a_mutable; /* ok */ const char **pointer_to_constant = &a_constant; /* ok */ pointer_to_constant = pointer_to_mutable; /* oops, are you sure? */ *pointer_to_constant = a_mutable; /* valid, but will screw things around */ 

The last line is valid, because pointer_to_constant is a mutable pointer to a mutable pointer to a constant character, but this can break things, since you are doing a_constant on a_mutable . This is why you are not allowed to receive pointer_to_constant contents of pointer_to_mutable .

+2
source

The first work example works because you convert the values โ€‹โ€‹of r char* to const char* , which is normal (mainly because you cannot assign rvalues). The second does not, because the target (not const const) of the pointer is always an lvalue.

Just try (possibly with a compiler) what operations you can do with char** , which work with const char** , and think about whether and what types are interchangeable.

0
source

All Articles