为什么编译器会抱怨分配?

cha*_*rre 0 c variable-assignment

在编译以下代码时,编译器会生成警告:

赋值从指针目标类型中丢弃'const'限定符

#include<stdio.h>

int main(void)
{
 char * cp;
 const char *ccp;
 cp = ccp;
}
Run Code Online (Sandbox Code Playgroud)

这段代码还可以(没有警告).为什么?

#include<stdio.h>

int main(void)
{
 char * cp;
 const char *ccp;
 ccp = cp;
}
Run Code Online (Sandbox Code Playgroud)

编辑:那为什么不行呢?

int foo(const char **p) 
{ 
  // blah blah blah ...
}

int main(int argc, char **argv)
{
 foo(argv);
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*lia 5

因为添加constness是一个"安全"的操作(你限制你可以对指向的对象做什么,这没什么大不了的),而删除constness则不是(你承诺不通过那个指针触摸指向的对象,现在你正试图收回你的承诺).


至于另外的问题,它在C-Faq中解释:http://c-faq.com/ansi/constmismatch.html.简单地说,允许转换将允许另一种"不安全"的行为:

int give_me_a_string(const char **p) 
{ 
    const char *str="asd";
    *p=str; // p is a pointer to a const pointer, thus writing
            // a in *p is allowed
}

int main()
{
    char *p;
    give_me_a_string(&ptrs); //< not actually allowed in C
    p[5]='a'; // wooops - I'm allowed to edit str, which I promised
              // not to touch
}
Run Code Online (Sandbox Code Playgroud)