Modifying array inside a function in C

Viewed 2910
// test.txt
50
13
124

-

void hi ( int *b, FILE *pfile ) {

    rewind ( pfile );
    int i;
    for( i = 0 ; i < 3 ; i++ ) {
         fscanf ( pfile, "%d", &b[i] );
    }
}

int main ( void ) {

    FILE *fp = fopen ( "test.txt", "r" );
    int a[10];  //putting extra size for test.

    hi ( &a[0], fp );   
    printf("%d,%d,%d\n", a[0], a[1], a[2]);

    fclose ( fp );
    return 0;
}

I'm trying to understand pointers when there's array involved. While I was testing the code above, I noticed that by putting a different index value such as hi ( &a[0], fp ) to hi ( &a[1], fp ) I get different results.

//result of [ hi ( &a[0], fp ) ] //result of [ hi ( &a[1], fp ) ] 50,13,124 junk#,50,13 .

I am really confused about the results because in the 'hi' function I specify the start of the array from i = 0 which should mean it's storing the value starting from a[0]. But it seems like putting 1 instead of 0 is somehow moving values aside. Why is this happening?

3 Answers
Related