This is what I came up with, but I always get a Run-Time Check Failure #2 – Stack around the variable ‘h’ was corrupted.
int mostCommonLetter(char s[]) {
int i=0, h[26],k=0, max=0, number=0;
while ( k < 26){
h[k] = '0';
k++;
}
while(s[i] != '\0'){
h[whichLetter(s[i])] = h[whichLetter(s[i])]+1;
i++;
}
h[26] = '\0';
for(i=0;h[i]!='\0';i++){
if(h[i] > max)
number=i;
}
return number;
}
You cannot do
h[26] = '\0';– h has 26 elements indexed 0..25. As you know the length of h you don’t need to 0-terminate it, simply dofor (i=0; i < 26; ++i)Also, are you certain
whichLetteralways returns a value in the 0..25 range? What does it do if it e.g. encounters a space?