简体   繁体   English

C:指针类型之间的非法转换:指向const unsigned char的指针 - >指向unsigned char的指针

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

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. send_str()函数还需要能够接受非const字符串。

(I am compiling for the PIC16F77 with the Hi-Tech-C compiler) (我正在使用Hi-Tech-C编译器编译PIC16F77)

Thanks 谢谢

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": 如果send_str()永远不需要改变它的输入,但可能在调用者的上下文中使用非常量的数据调用 ,那么你应该只使用参数const因为它只是说“我不会改变它”:

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

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. 你的编译器说你的发送被转换为char指针的const char指针。 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.) 在函数send_str更改其值可能会导致未定义的行为。(大多数情况下调用和调用函数不会由同一个人编写,其他人可能会使用您的代码并调用它来查看不正确的原型。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM