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.
CodePudding user response:
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) ;
CodePudding user response:
The answer should become clear by looking at the table of operator precedence.
As you can see in the table, the postfix operator has higher priority than the indirection operator *. (Please do not confuse the postfix operator with the prefix operator, as they have different priorities.)
Therefore, the expression
*pCharCount
is equivalent to:
*(pCharCount )
On the other hand, the * operator has higher priority than the = operator, so the expression
*pCharCount = 1
is equivalent to:
(*pCharCount) = 1
