Accessing array with index as 'char array element'

Whenever we need to increment the occurrences of the array elements, we mostly go with the below method. 

#include <stdio.h>
#define SIZE 5
#define RANGE 255

int main()
{
    char arr[SIZE] = "Ronni";
    int i = 0;
    int count[RANGE + 1] = {0};
    
    for (; arr[i]; i++) {
        ++count[arr[i]];
        printf("i %d arr[%d] %d count[%d] %d\n",i, i, arr[i], arr[i], count[arr[i]]);
    }
    return 0; 
} 

Output:

1
2
3
4
5
i 0 arr[0] 82 count[82] 1
i 1 arr[1] 111 count[111] 1
i 2 arr[2] 110 count[110] 1
i 3 arr[3] 110 count[110] 2
i 4 arr[4] 105 count[105] 1

Points for takeaway

Array index can also be char array where the char array is converted to ASCII value.






Comments