Array Values assigning wrong Array

Why does my Array assign values into the empty Array?
The "keylist.txt" file simply contains "2 14 74 8 36 4 11"
It clearly is assigned all zeros before I scan my file to get the values for the second array. I have no idea whats going on. Any help would be appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <stdio.h>

int main(){
    int keylist[6], guess_list[6], game = 1;
    char file_name[30];

    FILE * ifp;

    for(int i = 0; i<7; i++){
        keylist[i] = 0;
        guess_list[i] = 0;
    }


    ifp = fopen("keylist.txt", "r");
    for(int i=0; i<7; i++){
        printf("Guess list:%d\n", guess_list[i]);
    }
    for(int i=0; i<7; i++){
        fscanf(ifp, "%d", &keylist[i]);
    }

    for(int i=0; i<=6; i++){
        printf("guess: %d key: %d\n", guess_list[i], keylist[i]);
    }

return 0;
}
You only created arrays of 6 elements but your loops are assuming they have 7 elements.
The [6] in int keylist[6] is not the highest index. It's the number of elements. So the indices, which start at 0, can only go up to 5.
Dutch, I understand that but why does this code right here pick up all 7 values and prints them to the screen?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>

int main(){
    int keylist[6], guess_list[6];
    char file_name[30];

    FILE * ifp;

    for(int i=0; i<7; i++){
        keylist[i] = 0;
    }

    ifp = fopen("keylist.txt", "r");

    for(int i=0; i<7; i++)
        fscanf(ifp, "%d", &keylist[i]);

    for(int i=0;i<7;i++)
        printf("%d\n", keylist[i]);

    return 0;
}
Because C++ does not check that you are writing past the end of the array. But doing so is what is called "undefined behavior" and it is a serious error that can seem to work on some systems but not work on others, or possibly create a problem that will show up later on. If you compile your code on gcc with full warnings (-Wall -W -pedantic) it will tell you that you have undefined behavior.
Topic archived. No new replies allowed.