Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading