警告:赋值从指针目标类型中丢弃限定符

我写了以下代码:

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] != '\0') ) { letterCounter++; strIndex++; } pLastLetter[i] = &str[strIndex-1]; length[i] = letterCounter; letterCounter = 0; strIndex++; } } 

我在pLastLetter[i] = &str[strIndex-1];上收到了上述警告pLastLetter[i] = &str[strIndex-1];

pLastLetter is a pointers array that points to a char in str[].

任何人都知道为什么我得到它以及如何解决它?

好吧,正如你自己所说, pLastLetter是一个char *指针数组,而str是一个const char数组。 &str[strIndex-1]表达式的类型为const char* 。 不允许将const char*值赋给char *指针。 这会违反常规的规则。 事实上,你所做的是C中的一个错误.C编译器传统上将其报告为仅仅是一个“警告”,以避免破坏一些旧的遗留代码。

至于“如何解决它”……这取决于你想要做什么。 要么使pLastLetter成为const char*的数组,要么从str删除const

str是const,pLastLetter不是。 它说如果你这样做就会丢弃const限定符。