I am stuck with this mystery regarding for loop.
int abc[3], i, j;
for(j=0; j<3; j++);
printf("%d\n", j);
abc[j] = abc[j] + 3;
printf("%d \n", j);
Output:
3
6
Output should have been 3,3 as I’ve not changed value of j.
Adding 3 to the jth value of abc has resulted in change of value of j by 3. This happens only while exiting from a for loop and then trying to change the value of abc[j].
Maybe I am missing something pretty obvious. Any help would be much appreciated.
You have a buffer overflow since you declared your array to have size 3
int abc[3];yet you are indexing the 4th element; this is Undefined Behavior.What you are most likely seeing is that
jis located on the stack just past your arrayabcand so when you overflow one past the array withabc[3], you’re actually modifying the memory that containsj.*Note that nowhere in the C standard does it mention the word stack, this is an implementation detail and can change from system to system. This is partly the reason why it is Undefined Behavior and you are getting responses from people that they see two 3’s as output.