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

自古美人都是妖i 提交于 2019-12-22 16:03:14

问题


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


回答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 */



回答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.)



来源:https://stackoverflow.com/questions/21903648/c-illegal-conversion-between-pointer-types-pointer-to-const-unsigned-char-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!