"assignment discards 'const' qualifier" error on non-const pointer

24,669

Solution 1

input is a pointer to a constant char, and you're assigning it to a pointer to a non-constant char. This here might be an interesting reading for you.

Solution 2

you could also cast your 'input' variable with a (char*) type which would resolve the warning. just be careful using explicit casts like this so as not to modify constants themselves.

rest = (char*)input + i + 2;
Share:
24,669
yasar
Author by

yasar

I am an economics student, who enjoys programming.

Updated on November 23, 2020

Comments

  • yasar
    yasar over 3 years

    In the following function:

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

    I am getting assignment discards 'const' qualifier from pointer target type for the line rest = input + i + 2, however, as you can see, rest is not a constant pointer. What am I doing wrong here?

  • littleadv
    littleadv about 12 years
    @yasar11732 then you need char * const - the pointer is constant, not what it points to.
  • flarn2006
    flarn2006 almost 3 years
    I tried that and I still get the warning.