+ 11

Accesing array beyond it's size doesn't gives any error in c++ how?

i was declare a array size of 5. even i print 10 element in array it gives some random values not error message. this behavior same for all languages or c++ only. https://code.sololearn.com/c8uH1lyTLI7U/#cpp

19th Jul 2020, 7:16 AM
Azhagesanヾ(✿)
Azhagesanヾ(✿) - avatar
7 odpowiedzi
+ 3
C++ isn't safe with native arrays. Use std::array instead, with the '.at' method (it will throw an error) : std::array<int, 5> arr; std::cout << arr.at(10);
19th Jul 2020, 7:22 AM
Théophile
Théophile - avatar
+ 7
AZHAGESAN S You will get garbage value. I think it is only in C. Java will give exception.
19th Jul 2020, 7:21 AM
A͢J
A͢J - avatar
+ 5
AJ Anant #G3 thanks sir Théophile shows an error like array is not a member of std. Give me any working example. I'm new to c++
19th Jul 2020, 7:41 AM
Azhagesanヾ(✿)
Azhagesanヾ(✿) - avatar
+ 5
Thank you Théophile
19th Jul 2020, 9:05 AM
Azhagesanヾ(✿)
Azhagesanヾ(✿) - avatar
+ 4
Théophile now it gives out of range error that's fine. But this method doesn't give uninitialized error when using like arr [2]. Previous example gives uninitialized error. Is that possible to check both errors?
19th Jul 2020, 7:57 AM
Azhagesanヾ(✿)
Azhagesanヾ(✿) - avatar
+ 2
AZHAGESAN S you need to include the std header file: #include <array> At the beginning of the program.
19th Jul 2020, 7:46 AM
Théophile
Théophile - avatar
+ 2
It doesn't seem to be an error not to initialize an array in c++. If you want to initialize it with zero-values, you can do : std::array<int, 5> arr{}; It is explained in this Stack Overflow link : https://stackoverflow.com/questions/18295302/default-initialization-of-stdarray
19th Jul 2020, 8:59 AM
Théophile
Théophile - avatar