Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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!

like image 843
ojblass Avatar asked Dec 04 '22 15:12

ojblass


2 Answers

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)
{ 
}
like image 141
arul Avatar answered Dec 17 '22 14:12

arul


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**.

like image 25
bradtgmurray Avatar answered Dec 17 '22 14:12

bradtgmurray