Well the code counts and stores the frequency of each alphabet of str
to the integer array count
. After the execution of this function, count[index]
has the frequency of str[index]
. Let me explain what you want to know:
For Loop having the condition *(str+i):
*(str + i)
is equal to str[i]
, it refers to the i-th character of str
. character pointer's value is incremented to access the address of next index and then the address is dereferenced to get the index value which is now being pointed by the pointer str
.
Till what point will the Loop execute:
Loop will continue for each *(str+i)
until it finds a Null Terminator at *(str+i)
i.e. assume the following string:
char str[] = "abc";
what is stored in str
is now abc\0
so the loop will be executed until it reaches the \0
. The condition *(str+i)
is basically equal to *(str+i) != '\0';
What is the difference between count[i++] and count[i]++ :
count[i++]
is equal to *(count + i++)
that imposes a Post Increment to the address
stored in count
before using it. That means the value of (count+i)
is incremented by one and count starts pointing to the next index, once the statement is executed.
count[i]++
is equal to *(count + i)++
that imposes a Post Increment to the value
stored in the index pointed by (count + i)
. That means after the execution of this statement, the value of *(count+i)
is incremented by one BUT the count is still pointing to the current index.
In Your Case the statement used in the loop is:
count[*(str+i)]++;
By applying the Order of Precedence
- First of all
*(str+i)
will be executed that will give the value
stored at the address which is being pointed by (str+i)
- Now that
value
will be used as an index
of count and a Post Increment
will be imposed to count[index]
that means the value of *(count+index)
is incremented by one after the execution of the above statement.
Hope its pretty much cleared now.