Search code examples
cstringgccpointer-arithmetic

error: invalid conversion from 'const char*' to 'char*' when trying to use pointer arithmetics


I feel stupid for asking this question as the solution must be obvious. I get the following error

error: invalid conversion from 'const char*' to 'char*' [-fpermissive]
     char *subtopic = topic+strlen(mqtt_meta_ctrl_topic);

for the following code:

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

As you can see, I try to get a "view" into the topic-string with subtopic at an address which is still in the topic-string but a little further downstream. I guess my pointer arithmetic is a bit off but I can't figure out why because I don't change the const char *topic string.


Solution

  • topic is const char *, but your subtopic is char*.

     const char *subtopic = topic + whatever;
    
    printf("%.*s", topic_len-strlen(...)
    

    Note that strlen returns a size_t, but .* expects an int. You should do a cast here printf("%.*s", (int)(topic_len - strlen(...)).

    It might be better to use fwrite or such, instead of printf, for performance.