C post increment not working on a pointer but addition assignment does

I have a simple function to count words and characters taking two pointers and the file stream:

void countWordsAndChars(FILE *stream, int *pWordCount, int *pCharCount)
{
    int ch = getc(stream);
    while (ch != EOF)
    {
        if (!isspace(ch) && ch != '\n')
        {
            *pCharCount++; // Does not work
            *pCharCount += 1; // Works
        }
        else 
        {
            *pWordCount++; // Does not work
            *pWordCount += 1; // Works
        }
        ch = getc(stream);
    }
}

If I use the autoincrement operators (*pWordCount++) it doesnt work. But if I use the addition assignment (*pWordCount += 1) it does.

I’m coming from the web dev world and am pretty new to C. Please explain why.

Thanks.

>Solution :

They are different:

*pCharCount++; equals to *(pCharCount++) so it dereferences the pointer (which does not do anything) and then increases the pointer.

*pCharCount += 1; increases the object referenced by the pointer.

If you want to use postincrement operator you need to: (*pCharCount)++;

Leave a Reply