Changing an array inside a function in C

// 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 am trying to understand pointers when an array is involved. While I was testing the above code, I noticed that by adding another index value, for example 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 really got confused in the results, because in the "hi" function I specify the beginning of an array of i = 0 , which should mean that it stores a value starting with a[0] . But it seems that put 1 instead of 0 somehow moves the values ​​to the side. Why is this happening?

+8
c function arrays pointers
source share
3 answers

This may make more sense to you if you think of & as an operator that acts on a single element, just like - acts on a number to change sign. In this case, & takes the address of what you give it. In the case of &a[0] you take the address a[0] . In the case of &a[1] you take the address a[1] . In other words, you take the address of the various elements of the array. Thus, function b contains the address that you passed to it. As far as the function knows, what you pass is the "first" element of the array. He does not know anything about any of the previous elements.

+6
source share

In your second example, you have Undefined Behavior. You pass the address of the second element of the array. Then you scan all 10 items. But since you passed the address of the second element as the starting one, the last scanf writes an element that is outside the array, and this is an error.

enter image description here

I would advise if you are going to manipulate more than an array element, also pass the size of the array

 #define ARRAYSIZE(x) (sizeof(x) / sizeof(x[0])) void hi ( int *b, FILE *pfile, size_t size ) { rewind ( pfile ); int i; for( i = 0 ; i < size ; i++ ) { fscanf ( pfile, "%d", &b[i] ); } } 

and challenge

 hi ( a, fp, ARRAYSIZE(a)); 

or

 hi ( &a[0], fp, ARRAYSIZE(a)); 
+4
source share

You do not execute another size, but provide a pointer to the 1st element in the array, and then to the second element.

Since in the second case you pointed to the second element and tried to read 10 elements (starting from the second position), but only 9 valid elements when you start at the second, you then read into memory that it is not in the array.

+3
source share

All Articles