【问题标题】:"assignment discards 'const' qualifier" error on non-const pointer非常量指针上的“赋值丢弃'const'限定符”错误
【发布时间】:2012-04-11 20:24:30
【问题描述】:

在以下函数中:

char *mystrtok(const char *input, const char *delim,char *rest) {
    int i;
    for (i = 0; input[i] != *delim && input[i] != '\0'; ++i) {
        continue;
    }
    char *result = malloc(sizeof(char) * (i + 2));
    memcpy(result, input, i + 1);
    result[i + 1] = '\0';
    if (input[i + 1] != '\0') 
        rest = input + i + 2;
    else
        rest = NULL;
    return result;
}

我得到assignment discards 'const' qualifier from pointer target typerest = input + i + 2 行,但是,正如你所看到的,rest 不是一个常量指针。我在这里做错了什么?

【问题讨论】:

  • " 如您所见,rest 不是常量指针"。您不能将 const (input) 分配给非 const (rest) 成员。这正是错误消息所说的内容。您正试图将其清除 (discard),但您不能这样做。

标签: c pointers constants


【解决方案1】:

input 是一个指向常量字符的指针,您将它分配给一个指向 非常量 字符的指针。 This here 对你来说可能是一个有趣的读物。

【讨论】:

  • @yasar11732 那么你需要char * const - 指针是不变的,而不是它所指向的。
【解决方案2】:

您还可以使用 (char*) 类型转换您的“输入”变量,这将解决警告。小心使用像这样的显式转换,以免修改常量本身。

rest = (char*)input + i + 2;

【讨论】:

  • 我试过了,但我仍然收到警告。
【解决方案3】:

将原型更改为

char *mystrtok(const char *input, const char *delim, const char *rest);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多