【问题标题】:error: invalid conversion from 'const char*' to 'char*' when trying to use pointer arithmetics错误:尝试使用指针算术时从 'const char*' 到 'char*' 的无效转换
【发布时间】: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);
}

如您所见,我尝试使用subtopictopic-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


【解决方案1】:

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 可能会更好地提高性能。

【讨论】:

  • 确实如此。问题是我没有意识到 IF subtopic 只是 char(没有 const),然后我可以用简单的 *subtopic = '\0' 或类似的东西来更改主题变量的内存,这将绕过 const 的想法-ness :)
【解决方案2】:

请看下面的代码:

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

【讨论】:

    猜你喜欢
    • 2023-03-26
    • 1970-01-01
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    • 2022-11-13
    • 2021-01-30
    • 1970-01-01
    相关资源
    最近更新 更多