微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

错误:尝试使用指针算法时从“const char*”到“char*”的无效转换

如何解决错误:尝试使用指针算法时从“const char*”到“char*”的无效转换

我觉得问这个问题很愚蠢,因为解决方案必须是显而易见的。我收到以下错误

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);
}

如您所见,我尝试使用 topicsubtopic 字符串中的某个地址进行“查看”,该地址仍在主题字符串中,但位于更远的下游。我想我的指针算法有点偏离,但我不知道为什么,因为我没有更改 const char *topic 字符串。

解决方法

topicconst char *,但您的 subtopicchar*

 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 !'

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。