Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c - warning: assignment discards qualifiers from pointer target type

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 is a pointers array that points to a char in str[].

Anyone knows why I'm getting it and how to fix it?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Well, as you said yourself, pLastLetter is an array of char * pointers, while str is 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.

As for "how to fix it"... It depends on what you are trying to do. Either make pLastLetter an array of const char* or remove the const from str.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...