+ 1

Array accepts more data then mentioned.

code: { char a[10]; gets (a); cout <<a; } if I enter more than 10 character, the array accepts it and even displays all of them. How is it possible? The array length is 10 but accepts many elements.

12th Nov 2016, 7:36 AM
Piyush Yadav
Piyush Yadav - avatar
2 Respuestas
+ 2
There is no string or array boundary checking in C++. You should carefully use only memory you requested on array or string declaration. Answering your question: you are writing 10+ string chars to the memory starting from the address char *a. Then cout prints the string chars from a til the first \0 char. As result you see the 10+ long string on the screen. I would recommend to declare an int b = 42 right after your string, enter long string and print both a and b. You may see that b was changed, because it was overvritten with your input string bytes. Also if you declare int c = -1 before a[ ] you may cout << (a - 3) and see some weird output, including bytes of c.
12th Nov 2016, 8:52 AM
Alexey Shulga
Alexey Shulga - avatar
+ 2
If free space is available after the allocated memory... Then values can be added... That is limitation of gets... it gets everything... If you enter more non sense then the program terminates... as enough memory wasn't available
12th Nov 2016, 2:51 PM
Soutik
Soutik - avatar