Given that scanf has (const char *) in the documentation from Microsoft and the answer to this question what the heck is going when I do the same for (char **) promotion to (const char **)?
Basically why does this compile?
#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 won'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 thing to a pointer!
char** -> const char **
is dangerous, since you might end up accidentally modifying the underlying const
object.
The correct way to write what you want is:
void processargs(const char * const *p)
{
}
You're allowed to increase access restriction, you just can't decrease it. Going from a normal pointer to a const pointer is fine, going from a const pointer to a normal pointer is not.
The second example doesn't compile because you're not converting a pointer to a const pointer, you're converting from a pointer to one type (char*
) to another (const char*
). For example, you can change a char**
to a char* const*
, but not a const char**
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With