Explain the following scenario... | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Explain the following scenario...

char arr[5]; cin >> arr; // 0123456789 cout << arr << endl << arr[7] << endl; /* Output: 0123456779 7 And compiler gives no index_of_bound or segmentation fault... */

2nd Jan 2021, 6:11 PM
Sp Maurya
Sp Maurya - avatar
4 Answers
+ 3
Compiler is not required to check if access to array is out of bounds - in principle it might not have the required information at compilation time (if you access the array using a variable index) Checking the index in runtime is also not done - the c++ maxim is "you don't pay for what you don't use" so the correct programs don't have to slow down because of existence of the incorrect ones (whether it is a right approach here is another question, but we have what we have). When your program acesses the array elements out of its bounds its behavior is undefined, so anything can happen including the behavior you wanted (but it is also possible that the same code will work in a wrong way another time you run it) If you want bounds check you can use vector and access elements using v.at(i)
2nd Jan 2021, 6:40 PM
Volodymyr Chelnokov
Volodymyr Chelnokov - avatar
0
Your char array has max length of 5 but you are trying to access the element at index 7 that's why you are getting an error. Change arr[5] to arr[10]
2nd Jan 2021, 6:16 PM
Deekshant
Deekshant - avatar
0
Deekshant i know it should give error... thats the whole point compiler gives no error...
2nd Jan 2021, 6:27 PM
Sp Maurya
Sp Maurya - avatar
0
Deekshant try to do it in compiler... it will not give any error...
2nd Jan 2021, 6:28 PM
Sp Maurya
Sp Maurya - avatar