Sunday, August 19, 2012

C - counting the number of times a char appears in a string

Code: https://gist.github.com/3394648

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int** count_chars(char *s)
{
int **counts = (int**)malloc(256 * sizeof(int) * sizeof(char));
int i;
for(i = 0; i < 256; i++)
{
counts[i] = (int*)malloc(sizeof(int)*2);
counts[i][0] = i;
counts[i][1] = 0;
}
while(*s)
{
counts[(int)*s][1] += 1;
s++;
}
return counts;
}
int int_pair_asc(const void *a, const void *b){
int *first = *(int**)a;
int *second = *(int**)b;
return first[1] - second[1];
}
int int_pair_desc(const void *a, const void *b){
return (int_pair_asc(a, b) * -1);
}
int main(){
char msg[] = "I am a large brown bear who lives in the forest. My diet consists primarily of honey and spaceships.";
printf("string: '%s'\n", msg);
int **counts = count_chars(msg);
qsort(counts, 256, sizeof(int), int_pair_desc);
int i;
for(i = 0; i < 256; i++){
if(counts[i][1] > 0)
printf("Rank[%d]: '%c' - %d\n", i+1, counts[i][0], counts[i][1]);
}
return 0;
}
view raw countchars.c hosted with ❤ by GitHub
This was a nice exercise that helped me get more familiar with malloc and pointers.  I was really happy when I got the two dimensional array pointers working on the first try!