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

后端 未结 4 430
野性不改
野性不改 2021-01-13 18:53

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

4条回答
  •  没有蜡笔的小新
    2021-01-13 19:30

    Check if this clarifies for 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, since pointer_to_constant is a mutable pointer to a mutable pointer to a constant character, but it would break things since you are making a_constant point to a_mutable. That is why you are not allowed to make pointer_to_constant receive the contents of pointer_to_mutable.

提交回复
热议问题