【问题标题】:Initialization discards qualifiers from pointer target type初始化丢弃来自指针目标类型的限定符
【发布时间】:2011-01-19 22:59:42
【问题描述】:

我正在尝试打印我在link text 中提到的单链表的列表。它可以工作,但我确实收到了编译器警告:

Initialization discards qualifiers from pointer target type

(关于 start = head 的声明)和

return discards qualifiers from pointer target type

(在返回语句中)在此代码中:

/* Prints singly linked list and returns head pointer */
LIST *PrintList(const LIST *head) 
{
    LIST *start = head;

    for (; start != NULL; start = start->next)
        printf("%15s %d ea\n", head->str, head->count);

    return head;
}

我正在使用 XCode。有什么想法吗?

【问题讨论】:

  • 仅供参考,我已经让 gcc 打印了类似这样的不明警告,我认为这些警告是由 -Wwrite-strings 控制的。还有-Wdiscarded-qualifiers-Wcast-qual 和clang 的-Wincompatible-pointer-types-discards-qualifiers,看起来也很相关。

标签: c linked-list


【解决方案1】:

就是这个部分:

LIST *start = head;

函数的参数是一个指向常量const LIST *head的指针;这意味着您无法更改它所指向的内容。但是,上面的指针指向非常量;您可以取消引用并更改它。

它也必须是const

const LIST *start = head;

这同样适用于您的返回类型。


所有编译器都在说:“嘿,你对调用者说'我不会改变任何东西',但你正在为此开辟机会。”

【讨论】:

  • 愚蠢的问题,但是 const 返回类型是什么样的?我尝试在网上搜索,但似乎找不到。
  • @Crystal - const LIST *PrintList(const LIST *head) { ... }
  • The parameter for the function is a constant pointer - 不正确。 const LIST *head 将 head 声明为指向常量 LIST 的指针。见:c-faq.com/decl/constparm.html——也许这只是措辞上的误解。
  • 喜欢用自然语言解释它,就好像编译器会说话一样。很好的解释!
【解决方案2】:

在下面的函数中,会得到你遇到的警告。

void test(const char *str) {
  char *s = str;
}

有3个选择:

  1. 去掉param的const修饰符:

    void test(char *str) {
      char *s = str;
    }
    
  2. 将目标变量也声明为 const:

    void test(const char *str) {
      const char *s = str;
    }
    
  3. 使用类型转换:

    void test(const char *str) {
      char *s = (char *)str;
    }
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    • 2011-03-19
    • 2013-03-02
    • 1970-01-01
    相关资源
    最近更新 更多