just starting to learn C++, and sort of confusing about the following section of code:

int *getCharCountArray(char *str)
{
   int *count = (int *)calloc(sizeof(int), NO_OF_CHARS);
   int i;
   for (i = 0; *(str+i);  i++)
      count[*(str+i)]++;
   return count;
}

In specific, do not quite understand how the following two work?

for (i = 0; *(str+i);  i++)

and

count[*(str+i)]++;
for (i = 0; *(str+i);  i++)

this is a for loop, which will start with

i = 0

, and iterate through until the condition

*(str+i)

is met, and the iteration will move by one at a time as shown by the

i++

note: as far as i can remember the * indicates that its a pointer, correct me if im wrong

Edited 6 Years Ago by phoenix911: n/a

str is a pointer to a character array.
Assume char *str = "ABCDEFG"; The first character in the array, 'A', can be represented as *str -- contents of str *(str+0) -- contents of 0th element of str
Expanding this last one, *(str+3) -- contents of 3rd element of str: 'D'

Therefore, the for loop tests the character at (str+i) to see if the end of the string has been reached -- the ending \0 count[*(str+i)]++; uses the character at (str+i) as an index to increment a value in count
If i = 0, it increments count, or count[65]
If i = 4, it increments count, or count[69]

I believe it's a shortcut way of saying str[i] !='\0' since once the pointer hits the end of the string it will be null and therefore that statement *(str+i) will be false.

str is a pointer to a character array.
Assume char *str = "ABCDEFG"; The first character in the array, 'A', can be represented as *str -- contents of str *(str+0) -- contents of 0th element of str
Expanding this last one, *(str+3) -- contents of 3rd element of str: 'D'

Therefore, the for loop tests the character at (str+i) to see if the end of the string has been reached -- the ending \0 count[*(str+i)]++; uses the character at (str+i) as an index to increment a value in count
If i = 0, it increments count, or count[65]
If i = 4, it increments count, or count[69]

Thanks for the reply.
What still confused me is that:
In general, an array is indexed by 1, 2, 3,etc. And we can have sth like A[1], A[2],…
But here, the count array is indexed by A,B, C. Is that right?

Thanks for the reply.
What still confused me is that:
In general, an array is indexed by 1, 2, 3,etc. And we can have sth like A[1], A[2],…
But here, the count array is indexed by A,B, C. Is that right?

Almost. It's indexed by 'A', 'B', 'C'. Small detail but very important.

This article has been dead for over six months. Start a new discussion instead.