My program adds to the counter variable when I use "count+=1" and doesn't when I use "count++"

I’m practicing pointers right now. The task is simple, count the number of instances of the letter c in an array and print the amount of times it occurred.I assigned a pointer to a counter variable in a function outside of main. For some reason, my program doesn’t count when I use *count++;

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

What I expected to happen:
// c found 3 times

What I got
// c found 0 times

>Solution :

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 by count by 1, and return the original value". This expression modifies the value stored at the memory location pointed to by count, and then returns the original value before the increment.

*count++ is equivalent to *(count++), which means "return the value pointed to by count, and then increment count to point to the next memory location". This expression does not modify the value stored at the memory location pointed to by count, 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 variable count by incrementing it by 1 for each occurrence of the key 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 quetion was already answer here!

Leave a Reply