something strange happening when initializing an array from a file.

This is a discussion on something strange happening when initializing an array from a file. within the C Programming forums, part of the General Programming Boards category; Code: #include <stdio.h> int main(){ FILE *ifp; ifp = fopen ("input.txt", "r"); int alpha, scores [3], i, bravo[18], charlie; fscanf ...

  1. #1
    Registered User
    Join Date
    Mar 2012
    Posts
    4

    something strange happening when initializing an array from a file.

    Code:
    #include <stdio.h>
    
    int main(){
        FILE *ifp;
        ifp = fopen ("input.txt", "r");
        int alpha, scores [3], i, bravo[18], charlie;
    
        fscanf (ifp, "%d", &alpha);
        printf ("alpha = %d\n", alpha);
    
        for (i = 0; i<18; i++){
        fscanf (ifp, "%d", &bravo[i]);
        printf (" bravo = %d\n", bravo[i]);
        }
    
        printf ("alpha = %d", alpha);
        
        for (i=0; i < 4; i++)
        scores[i] = 0;
    
        printf ("alpha = %d", alpha);
    
    return 0;
    }
    input file:
    1
    2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
    3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
    4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4



    When I run this code, the value of alpha is '1' after the initial scanf. But after I get down to this loop to initialize the 'scores' array:

    for (i=0; i < 4; i++)
    scores[i] = 0;

    The value changes to '0'. I don't understand why this initialization loop would change the value of alpha. Any help would be appreciated.

  2. #2
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    You're writing beyond the end of the array (by one). In fact, you're writing onto alpha off the end of scores, that's why alpha is zeroed.

    So you're loop test should be i < 3 so it goes 0, 1, 2, but NOT 3, since the array only has 3 elements.
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Strange things happening with counter
    By cnewbie1 in forum C Programming
    Replies: 4
    Last Post: 05-31-2011, 09:48 AM
  2. problem initializing a double array for large array
    By gkkmath in forum C Programming
    Replies: 4
    Last Post: 08-25-2010, 09:26 PM
  3. initializing array .
    By transgalactic2 in forum C Programming
    Replies: 24
    Last Post: 04-20-2009, 10:56 AM
  4. Initializing a 2D Array in C
    By Cell in forum C Programming
    Replies: 20
    Last Post: 03-21-2009, 01:31 PM
  5. I/O File Don`t know what´s happening
    By Rafa in forum C++ Programming
    Replies: 3
    Last Post: 10-21-2002, 04:15 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21