tags:

views:

91

answers:

2

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

and i'm getting the above worning 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?

thanks!

+3  A: 

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.

AndreyT
thank you very much for the quick answer, which brings me to another quetion: if this is the function:void buildArrays(char *pLastLetter[],int length[], int size, const char str[]) is it ok to call to this function by:buildArrays(pLastLetter[],length,str) where str is of type char* and not const char*?compiler does not output a warning, however can it cause an undefined behaviour?thank you
rob
@Asher: `const T*` is just a promise not to modify the pointee through that pointer, so you can implicitly convert a `T*` to `const T*` fine. (This does fall down for pointers-to-pointers, though. See http://c-faq.com/ansi/constmismatch.html .)
jamesdlin
+1  A: 

str is const, pLastLetter isn't. It's saying the const qualifier is discarded if you do this.

Shawn D.