Yesterday, my answer got deleted by a moderator (@sideshowbarker). Being new to Stack Overflow, it's possible I broke a rule without knowing it, but could I get the reason so that I don’t repeat my mistakes? Thanks.
It was an answer for this question and here is my answer.
I am pretty sure my answer wasn’t a duplicate since I answered shortly after the question was asked and did not copy anyone for it. Also my answer provided corrected code and a link to a similar question as well as an explanation of the answer, so I didn’t find the rule I broke.
Since I am not sure my answer is visible, I am going to post what I wrote here.
The expressions
(*count)++
and*count++
may seem similar, but they have different meanings and can produce different results.
(*count)++
is equivalent to(*count) += 1
, which means "increment the value pointed to bycount
by 1, and return the original value". This expression modifies the value stored at the memory location pointed to bycount
, and then returns the original value before the increment.
*count++
is equivalent to*(count++)
, which means "return the value pointed to bycount
, and then incrementcount
to point to the next memory location". This expression does not modify the value stored at the memory location pointed to bycount
, but rather advances the pointer to the next location in the memory.In the case of the code posted in the question, using
*count++
in the loop would not update the value of the variable count in the calling function, because it only changes the pointer locally within the loop. On the other hand, using(*count)++
correctly updates the value of the variablecount
by incrementing it by 1 for each occurrence of thekey
character in the input string.Here is a correction of your code that works as intended
#include <stdio.h> #include <string.h> void q(char S[], char key, int *count){ int i, n; *count=0; n=strlen(S); for(i=0;i<n;i++){ if(S[i]==key){ (*count)++; printf("found at index %d\n", i); } } } void main(){ char S[]={'a','b','c','b','c','e','d','c','f'}; char key='c'; int *counter,count; counter=&count; q(S,'c', counter); printf("C found %d times\n", *counter); } ```> PS: The question was already answered [here](https://stackoverflow.com/questions/20931206/incrementing-pointers-value-doesnt-work/)!