C语言 警告:赋值会丢弃来自指针目标类型的限定符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3479770/
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
warning: assignment discards qualifiers from pointer target type
提问by Asher Saban
I wrote the following code:
我写了以下代码:
void buildArrays(char *pLastLetter[],int length[], int size, const char str[]) {
int i;
int strIndex = 0;
int letterCounter = 0;
for (i=0; i<size; i++) {
while ( (str[strIndex] != SEPERATOR) || (str[strIndex] != '##代码##') ) {
letterCounter++;
strIndex++;
}
pLastLetter[i] = &str[strIndex-1];
length[i] = letterCounter;
letterCounter = 0;
strIndex++;
}
}
and I'm getting the above warning on pLastLetter[i] = &str[strIndex-1];
我收到了上述警告 pLastLetter[i] = &str[strIndex-1];
pLastLetter is a pointers array that points to a char in str[].
pLastLetter is a pointers array that points to a char in str[].
Anyone knows why I'm getting it and how to fix it?
任何人都知道为什么我得到它以及如何解决它?
回答by AnT
Well, as you said yourself, pLastLetteris an array of char *pointers, while stris an array of const char. The &str[strIndex-1]expression has type const char*. You are not allowed to assign a const char*value to a char *pointer. That would violate the rules of const-correctness. In fact, what you are doing is an error in C. C compilers traditionally report it as a mere "warning" to avoid breaking some old legacy code.
那你自己说的,pLastLetter是数组char *指针,同时str是一个数组const char。该&str[strIndex-1]表达式的类型为const char*。你是不是允许在指定const char*值的char *指针。这将违反常量正确性规则。事实上,您正在做的是 C 中的错误。C 编译器传统上将其报告为仅仅是“警告”,以避免破坏一些旧的遗留代码。
As for "how to fix it"... It depends on what you are trying to do. Either make pLastLetteran array of const char*or remove the constfrom str.
至于“如何修复它”......这取决于你想要做什么。制作pLastLetter一个数组const char*或删除constfrom str。
回答by Shawn D.
str is const, pLastLetter isn't. It's saying the const qualifier is discarded if you do this.
str 是常量, pLastLetter 不是。如果您这样做,则表示 const 限定符将被丢弃。

