【发布时间】:2021-05-19 06:26:59
【问题描述】:
我觉得问这个问题很愚蠢,因为解决方案必须是显而易见的。我收到以下错误
error: invalid conversion from 'const char*' to 'char*' [-fpermissive]
char *subtopic = topic+strlen(mqtt_meta_ctrl_topic);
以下代码:
void HandleIncomingMQTTData(const char* topic, const int topic_len, const char* data, const int data_len)
{
// Determine subtopic
char *subtopic = topic+strlen(mqtt_meta_ctrl_topic);
printf("%.*s", topic_len-strlen(mqtt_meta_ctrl_topic), subtopic);
}
如您所见,我尝试使用subtopic 对topic-string 进行“查看”,该地址仍在主题字符串中,但在下游一点。我想我的指针算法有点不对,但我不知道为什么,因为我没有更改 const char *topic 字符串。
【问题讨论】:
-
const不能因为喜欢就扔掉。 -
如果你真的想删除
const-ness,我想你可以用char *subtopic = (char *) (topic+strlen(mqtt_meta_ctrl_topic));在C语言中完成,但你可能也会收到关于这个的警告。您现在似乎不需要删除函数中的const-ness。 -
我总是对
char是 const 还是指针是 const 感到困惑。似乎这里char是 const 并且不能分配给可以修改的字符(不是 const)。 -
@PaulOgilvie Classic conundrum.
-
编译器错误很容易阅读和理解,它也指出了错误的确切位置。 “从 'const char*' 到 'char*' 的无效转换”的哪一部分不清楚?
标签: c string gcc pointer-arithmetic