Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

c - Initialization discards qualifiers from pointer target type

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
", head->str, head->count);

    return head;
}

I am using XCode. Any thoughts?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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."


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...