C: Illegal conversion between pointer types: pointer to const unsigned char -> pointer to unsigned char

12,073

Solution 1

You need to add a cast, since you're passing constant data to a function that says "I might change this":

send_str((char *) mystr);  /* cast away the const */

Of course, if the function does decide to change the data that is in reality supposed to be constant (such as a string literal), you will get undefined behavior.

Perhaps I mis-understood you, though. If send_str() never needs to change its input, but might get called with data that is non-constant in the caller's context, then you should just make the argument const since that just say "I won't change this":

void send_str(const char *str);

This can safely be called with both constant and non-constant data:

char modifiable[32] = "hello";
const char *constant = "world";

send_str(modifiable);  /* no warning */
send_str(constant);    /* no warning */

Solution 2

change the following lines

void send_str(char * str){
// send it
}

TO

void send_str(const char * str){
// send it
}

your compiler is saying that the const char pointer your sending is being converted to char pointer. changing its value in the function send_str may lead to undefined behaviour.(Most of the cases calling and called function wont be written by the same person , someone else may use your code and call it looking at the prototype which is not right.)

Share:
12,073
CL22
Author by

CL22

Updated on June 05, 2022

Comments

  • CL22
    CL22 almost 2 years

    The following code is producing a warning:

    const char * mystr = "\r\nHello";
    void send_str(char * str);
    
    void main(void){
        send_str(mystr);
    }
    void send_str(char * str){
        // send it
    }
    

    The error is:

    Warning [359] C:\main.c; 5.15 illegal conversion between pointer types
    pointer to const unsigned char -> pointer to unsigned char
    

    How can I change the code to compile without warnings? The send_str() function also needs to be able to accept non-const strings.

    (I am compiling for the PIC16F77 with the Hi-Tech-C compiler)

    Thanks