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

CL2*_*L22 2 c warnings pointers const type-conversion

以下代码生成警告:

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

void main(void){
    send_str(mystr);
}
void send_str(char * str){
    // send it
}
Run Code Online (Sandbox Code Playgroud)

错误是:

Warning [359] C:\main.c; 5.15 illegal conversion between pointer types
pointer to const unsigned char -> pointer to unsigned char
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢

unw*_*ind 5

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

send_str((char *) mystr);  /* cast away the const */
Run Code Online (Sandbox Code Playgroud)

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

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

void send_str(const char *str);
Run Code Online (Sandbox Code Playgroud)

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

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

send_str(modifiable);  /* no warning */
send_str(constant);    /* no warning */
Run Code Online (Sandbox Code Playgroud)


KAR*_*HAT 5

更改以下行

void send_str(char * str){
// send it
}
Run Code Online (Sandbox Code Playgroud)

void send_str(const char * str){
// send it
}
Run Code Online (Sandbox Code Playgroud)

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