更新时间:2023-10-24 15:28:40
您需要添加强制类型转换,因为您要将常量数据传递给表示我可能会更改"的函数:
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 */