How do i fix the code to include the appropriate bounds checking.
~ #include int main(void) { int vals[10];
size_t count;
size_t which;
cout << "How many values should be stored in the array?” <<endl;
cin >> count;
for (size_t i = 0; i < count; i++)
{ vals[i] = count - i; }
cout << "Which value do you wish to retrieve? ";
cin >> which;
cout << "Your value is " << vals[which] << endl;
return 0;
} ~
You can use std::size
to check the number of elements in the array before indexing:
#include <algorithm>
#include <iterator>
//...
std::cin >> count;
count = std::min(std::size(vals), count);
for (size_t i = 0; i < count; i++)
vals[i] = count - i;
//...
if(which < count)
std::cout << "Your value is " << vals[which] << "\n";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.