问题描述
我觉得问这个问题很愚蠢,因为解决方案必须是显而易见的。我收到以下错误
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);
}
如您所见,我尝试使用 topic
对 subtopic
字符串中的某个地址进行“查看”,该地址仍在主题字符串中,但位于更远的下游。我想我的指针算法有点偏离,但我不知道为什么,因为我没有更改 const char *topic
字符串。
解决方法
topic
是 const char *
,但您的 subtopic
是 char*
。
const char *subtopic = topic + whatever;
printf("%.*s",topic_len-strlen(...)
请注意,strlen
返回 size_t
,但 .*
需要 int
。你应该在这里printf("%.*s",(int)(topic_len - strlen(...))
做演员。
为了提高性能,最好使用 fwrite
之类的,而不是 printf
。
查看下面的代码:
#include <stdio.h>
#include <string.h>
char mqtt_meta_ctrl_topic[100] = "Hello world !";
const char *t = "Have a good day !";
const char *d = "R2D2 & C3P0";
void HandleIncomingMQTTData(const char* topic,const int topic_len,\
const char* data,const int data_len)
{
printf("topic = '%s',topic_len = %d\n",topic,topic_len);
printf("topic = %ld\n",(unsigned long int)topic);
int x = strlen(mqtt_meta_ctrl_topic);
printf("x = %d\n",x);
// Determine subtopic
const char *subtopic = topic + x;
printf("subtopic = %ld,topic + x = %ld\n",(unsigned long int)(subtopic),\
(unsigned long int)(topic+x));
printf("topic_len - x = %d\n",topic_len - x);
printf("subtopic = '%.*s'",topic_len - x,subtopic);
}
int main(){
HandleIncomingMQTTData(t,(const int)strlen(t),d,(const int)strlen(d));
return(0);
}
输出如下,没有编译器警告或错误:
topic = 'Have a good day !',topic_len = 17
topic = 4196152
x = 13
subtopic = 4196165,topic + x = 4196165
topic_len - x = 4
subtopic = 'ay !'