简体   繁体   中英

Using histogram to find the most common letter in an array

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 do for (i=0; i < 26; ++i)

Also, are you certain whichLetter always returns a value in the 0..25 range? What does it do if it eg encounters a space?

This writes past the end of the array:

h[26] = '\0';

Make the for loop depend on the length rather than the last character:

for(i=0;i<26;i++){
    if(h[i] > max)
        number=i;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM