C:指针类型之间的非法转换:指向常量unsigned char的指针->;指向无符号字符的指针
以下代码正在生成警告:C:指针类型之间的非法转换:指向常量unsigned char的指针->;指向无符号字符的指针,c,pointers,type-conversion,warnings,constants,C,Pointers,Type Conversion,Warnings,Constants,以下代码正在生成警告: 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 cons
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()函数还需要能够接受非常量字符串。
(我正在用Hi-Tech-C编译器编译PIC16F77)
谢谢您需要添加强制转换,因为您正在将常量数据传递给一个表示“我可能会更改此设置”的函数: 当然,如果函数确实决定更改实际上假定为常量的数据(例如字符串文字),则会得到未定义的行为 也许我误解了你。如果
send_str()
永远不需要更改其输入,但可能会使用调用方上下文中的非常量数据调用,那么您应该只使用参数const
,因为它只会说“我不会更改它”:
可以使用常量和非常量数据安全地调用:
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
}
到
您的编译器表示您发送的const char指针正在转换为char指针。在函数
send\u str
中更改其值可能会导致未定义的行为。(调用和调用函数的大多数情况不会由同一个人编写,其他人可能会使用您的代码,并在原型不正确的情况下调用。)Achar*
可以转换为const char*
,但反之亦然。所以只需更改send_str
以获取const char*
。谢谢!为什么它可以被转换成一种方式而不是另一种方式?考虑什么是<代码> const <代码>意味着:一个“只读”变量。将可写变量视为只读变量是完全可以的,但反之亦然。@Jodes:因为mystr
指向(又称:它包含的地址)包含\r\nHello
的只读内存。该内存无法更改,因此指针是const
指针。如果将其传递给一个接受非常量的函数,则应该允许该函数将字符串char*arg
指向的值更改为。这在常量字符*
中是不允许的。rwchar*
,传递给一个函数,由于参数为const char*
“发誓”不更改字符串,因此它当然不是问题asnot touch char*var
和char*some_str
astouch or not char*some_str
可以读写非const
指针,如果这是一个选项的话,将send_str函数重写为使用const
,这是更好的做法。此外,@Lundin同意,我在那里编辑了const
,我看错了问题的要求。并删除了main()
注释,谢谢。
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
}