繁体   English   中英

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

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

以下代码生成警告:

const char * mystr = "\r\nHello";
void send_str(char * str);

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

错误是:

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

如何在没有警告的情况下将代码更改为编译? send_str()函数还需要能够接受非const字符串。

(我正在使用Hi-Tech-C编译器编译PIC16F77)

谢谢

您需要添加强制转换,因为您将常量数据传递给“我可能会更改此”的函数:

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

当然,如果函数确实决定更改实际上应该是常量的数据(例如字符串文字),那么您将获得未定义的行为。

不过,也许我误解了你。 如果send_str()永远不需要改变它的输入,但可能在调用者的上下文中使用非常量的数据调用 ,那么你应该只使用参数const因为它只是说“我不会改变它”:

void send_str(const char *str);

使用常量和非常量数据可以安全地调用它:

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

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

更改以下行

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

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

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

暂无
暂无

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

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