1

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:

Entering only 1's

Entering only 2's

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Ahh I see the error and how to fix it now. But why does this change the "i" variable within the loop? Likewise, why does inputting numbers greater than 3 overcome this problem too?
Short answer: Undefined behavior is undefined. Longer answer: intArray[4] is probably the same piece of memory as i, so you're overwriting i. As for numbers > 3, interesting. >4 I'd (since i wouldn't be < 5 the loop would stop).
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.