0

I have declared the length of array as 4. But after assigning a[21]=56, is not giving me error. However, the output comes to be 56.

 #include<stdio.h>
int main(){
int a[4]={10,20,30,40};
a[20]=57;
printf("%d",a[20]); }
  • That is because accessing an array out of range is invoking **UB** (*Undefined Behavior*). It will never result in a compilation error. The fact that you actually get something is probably by pure luck. – alex01011 Oct 03 '21 at 14:16
  • What did you expect to happen? If you expected an error message saying something like `array access out of bounds`, it turns out your expectation is quite incorrect for C. If you expected something weird to happen, well: something weird *did* happen! – Steve Summit Oct 03 '21 at 14:29
  • 1
    See also [this answer](https://stackoverflow.com/questions/57247807/difference-in-storage-of-memory-in-string-and-an-integer-array-in-c-after-using/57252388#57252388). – Steve Summit Oct 03 '21 at 14:34
  • So it means we can assign value to an undefined length array? – Yogesh Singh Rawat Oct 04 '21 at 16:42

0 Answers0