Thread: Problem with array initialization, possible windows-1252 errors

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    4

    Problem with array initialization, possible windows-1252 errors

    This code is supposed to count the number of occurrences of each lower-case letter of the alphabet for any input. It should ignore other inputs and stop when EOF is read. It works fine for every letter except z. If you run it you'll find that it displays an outrageous value for z occurrences.

    So please, if you will, school me on my errors. I'm new to this and can't seem to figure it out.


    Code:
    #include<stdio.h>
    
    int main() {
        int alphabet[25] = {0};
        char c = 0;
        int d;
    
        for(d = 0; d <= 25; d++) {
            printf("%c\tarray[%d]\t%d\n", d + 'a', d, alphabet[d]);
        }
    
        while(1) {
            c = getchar();
    
            if(c >= 97 && c <= 122) {
                printf("DEBUG entered storage\n");
                printf("c = %c, %d, array %d\n", c, c, c - 'a');
                alphabet[c-'a']++;
                printf("c = %c, %d, array %d\n", c, c, c - 'a');
            }
    
            if(c == EOF) {
                break;
            }
        }
    
        printf("Lower-case letter frequencies:\n");
    
        for(d = 0; d <= 25; d++) {
            printf("%c\tarray[%d]\t%d\n", d + 'a', d, alphabet[d]);
        }
    
        return 0;
    }

  2. #2
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    Code:
    int alphabet[25] = {0};
    How many letters are there in the alphabet?

  3. #3
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,059
    You're going out of bounds.

  4. #4
    Registered User
    Join Date
    Oct 2010
    Posts
    4
    The array is only to 25, but there are 0 - 25 places (a total of 26), no?

  5. #5
    Registered User
    Join Date
    Oct 2010
    Posts
    4

    Talking

    OK, yeah, I can't believe I just did that. Thank you all very much. Problem solved!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A question related to strcmp
    By meili100 in forum C++ Programming
    Replies: 6
    Last Post: 07-07-2007, 02:51 PM
  2. Question..
    By pode in forum Windows Programming
    Replies: 12
    Last Post: 12-19-2004, 07:05 PM
  3. Replies: 6
    Last Post: 10-21-2003, 09:57 PM
  4. Menu Item Caption - /a for right aligned Accelerator?
    By JasonD in forum Windows Programming
    Replies: 6
    Last Post: 06-25-2003, 11:14 AM
  5. FlashWindowEx not declared?
    By Aidman in forum Windows Programming
    Replies: 3
    Last Post: 05-17-2003, 02:58 AM

Tags for this Thread