Initialization discards qualifiers from pointer target type

女生的网名这么多〃 提交于 2019-12-28 13:41:07

问题


I'm trying to print the list of a singly linked list that I referred to in link text. It works, but I do get the compiler warnings:

Initialization discards qualifiers from pointer target type

(on declaration of start = head) and

return discards qualifiers from pointer target type

(on return statement) in this code:

/* 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;
}

I am using XCode. Any thoughts?


回答1:


It's this part:

LIST *start = head;

The parameter for the function is a pointer to a constant, const LIST *head; this means you cannot change what it is pointing to. However, the pointer above is to non-const; you could dereference it and change it.

It needs to be const as well:

const LIST *start = head;

The same applies to your return type.


All the compiler is saying is: "Hey, you said to the caller 'I won't change anything', but you're opening up opportunities for that."




回答2:


In following function, would get the warning that you encountered with.

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

There are 3 choices:

  1. Remove the const modifier of param:

    void test(char *str) {
      char *s = str;
    }
    
  2. Declare the target variable also as const:

    void test(const char *str) {
      const char *s = str;
    }
    
  3. Use a type convert:

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


来源:https://stackoverflow.com/questions/2316387/initialization-discards-qualifiers-from-pointer-target-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!