-1
int a[5];
    for(int i=0;i<12;i++)
    {
        printf("enter element #%d: ",i);
        scanf("%d",&a[i]);
    }
  1. I expected this to give me an error, but didn't give
  2. It does not take the input when the value of i is 8 i.e., for the 9th element. It just jumps when i=8
lgrams
  • 9
  • 2

2 Answers2

1

When you write past the bounds of an array, you invoke undefined behavior. That means the compiler makes no guarantees regarding what the program will do. It may crash, it may output strange results, or it may appear to work properly.

Just because the program could crash doesn't mean it will.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • It could be added that the behaviour of the program strongly depends on what kind of data is stored behind the `a`array. If the memory is unused everything seems right, if the memory is used then the program may crash or result in faulty behaviour in some unrelated code. A crash would the best option as it informs you about the bug. – Wör Du Schnaffzig Dec 04 '20 at 14:07
0

in your for loop ,your final value of control is 11 and the size of your array is 5,so you fill in the array 11 elements and you array contains only 5 boxes in memory ,your answer is like this :

#include<stdio.h>

int main()
{
    int a[5];
    for(int i=0;i<5;i++)
    {
        printf("enter element #%d: ",i);
        scanf("%d",&a[i]);
    }
}
MED LDN
  • 684
  • 1
  • 5
  • 10
  • Could you fix the hardcoded array limit so that the loop stays valid if the array size would be changed? – Wör Du Schnaffzig Dec 04 '20 at 14:10
  • @pqans,Yes of course,please work with this rule: (The size of array =Final value of control in for loop - First value of control in for loop +1) – MED LDN Dec 04 '20 at 14:15
  • I meant to either isolate the literal number `5` to some named constant or use the sizeof operator. I think a proper answer should consider this instead of providing the same literal more than one time. – Wör Du Schnaffzig Dec 04 '20 at 14:31