Reputation: 23
I'm trying to add elements to an array with a for loop in C, however something strange is happening. The i variable is effected by the numbers input using scanf.
int intArray[4];
int i;
printf("Input 5 numbers\n");
for(i=0;i<5;i++){
scanf("%d", &intArray[i]);
printf("i: %d\n",i);
}
Examples of outputs:
And any number greater than 3 input constantly works as intended or any number inserted greater than 3 when i = 3
I don't understand why i changes in this for loop in this way.
Any help would be appreciated.
Upvotes: 1
Views: 65
Reputation: 58
Well, arrays are zero based, so in your case i < 5 will result (i from 0 to 4) which is invalid and out of index, cuz it is supposed to be (i from 0 to 3 - 4 elements)
Upvotes: 0
Reputation: 29266
intArray[4]
has indexes 0, 1, 2, 3. Your for loop's end condition is i<5
, so it uses index 4, which is past the end of the array, and probably coincides with the variable i
.
Upvotes: 1