初始化会丢弃指针目标类型的限定符

Cry*_*tal 35 c linked-list

我正在尝试打印链接文本中提到的单链表的列表.它工作,但我得到编译器警告:

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;
}
Run Code Online (Sandbox Code Playgroud)

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

GMa*_*ckG 71

这是这部分:

LIST *start = head;
Run Code Online (Sandbox Code Playgroud)

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

它也需要const:

const LIST *start = head;
Run Code Online (Sandbox Code Playgroud)

这同样适用于您的退货类型.


所有的编译器都说:"嘿,你对打电话者说'我不会改变任何东西',但你正在为此开辟机会."

  • @Crystal - `const LIST*PrintList(const LIST*head){...}` (5认同)
  • 当它以自然语言解释时,喜欢它,就好像编译器可以说话一样。很好的解释! (2认同)

Eri*_*ang 21

在以下函数中,将获得您遇到的警告.

void test(const char *str) {
  char *s = str;
}
Run Code Online (Sandbox Code Playgroud)

有3种选择:

  1. 删除param的const修饰符:

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

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

    void test(const char *str) {
      char *s = (char *)str;
    }
    
    Run Code Online (Sandbox Code Playgroud)