C:指针类型之间的非法转换:指向const 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()
函数还需要能够接受非常量字符串.
How can I change the code to compile without warnings? The send_str()
function also needs to be able to accept non-const strings.
(我正在使用Hi-Tech-C编译器为PIC16F77进行编译)
(I am compiling for the PIC16F77 with the Hi-Tech-C compiler)
谢谢
推荐答案
您需要添加强制类型转换,因为您要将常量数据传递给表示我可能会更改"的函数:
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.
不过,也许我误会了你.如果send_str()
永远不需要更改其输入,但是可能会在调用者的上下文中使用非恒定数据来调用,那么您应该仅使用参数const
,因为这只是说不会改变这一点":
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 */
这篇关于C:指针类型之间的非法转换:指向const unsigned char的指针->指向无符号字符的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!