C语言 初始化丢弃来自指针目标类型的限定符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2316387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Initialization discards qualifiers from pointer target type
提问by Crystal
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:
我正在尝试打印我在link text 中引用的单链表的列表。它有效,但我确实收到了编译器警告:
Initialization discards qualifiers from pointer target type
Initialization discards qualifiers from pointer target type
(on declaration of start = head) and
(在声明 start = head 时)和
return discards qualifiers from pointer target type
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?
我正在使用 XCode。有什么想法吗?
回答by GManNickG
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.
该函数的参数是一个指向一个常数,const LIST *head; 这意味着您无法更改它所指向的内容。但是,上面的指针是指向非常量的;你可以取消引用它并改变它。
It needs to be constas well:
它也需要const:
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."
编译器只是说:“嘿,你对调用者说‘我不会改变任何东西’,但你正在为此打开机会。”
回答by Eric Wang
In following function, would get the warning that you encountered with.
在以下函数中,将收到您遇到的警告。
void test(const char *str) {
char *s = str;
}
There are 3 choices:
有3种选择:
Remove the const modifier of param:
void test(char *str) { char *s = str; }Declare the target variable also as const:
void test(const char *str) { const char *s = str; }Use a type convert:
void test(const char *str) { char *s = (char *)str; }
移除 param 的 const 修饰符:
void test(char *str) { char *s = str; }将目标变量也声明为 const:
void test(const char *str) { const char *s = str; }使用类型转换:
void test(const char *str) { char *s = (char *)str; }

