【问题标题】:Why does the compiler complain about the assignment?为什么编译器抱怨分配?
【发布时间】:2015-02-27 16:04:17
【问题描述】:

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

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

#include<stdio.h>

int main(void)
{
 char * cp;
 const char *ccp;
 cp = ccp;
}

而且这段代码没问题(没有警告)。为什么?

#include<stdio.h>

int main(void)
{
 char * cp;
 const char *ccp;
 ccp = cp;
}

编辑:那为什么不行呢?

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

int main(int argc, char **argv)
{
 foo(argv);
}

【问题讨论】:

  • 为了防止(或至少警告)您尝试更改常量数据。

标签: c variable-assignment


【解决方案1】:

因为添加 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
}

【讨论】:

    【解决方案2】:

    在第一种情况下,您将获取一个指向不得修改的数据的指针 (const),并将其分配给一个允许修改其数据的指针。坏而危险。

    在第二种情况下,您将一个非常量指针分配给一个指针,该指针可能会导致更少比原来的麻烦。您不会对任何有害、非法或未定义的行为敞开心扉。

    【讨论】:

      猜你喜欢
      • 2012-09-12
      • 2012-03-28
      • 2016-11-01
      • 2016-04-22
      • 1970-01-01
      • 2012-06-19
      • 2019-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多