The philosophical question is, should the simple examples simply spit out
new
, or should they remind about resource management and input validation too? Hence, a (futile) variation (since STL has
containers too):
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include <iostream>
#include <memory>
int main()
{
int n = 0;
std::cout << "Please enter the size of n: ";
if ( std::cin >> n && 0 < n )
{
std::unique_ptr<int[]> h( new int[n] );
}
return 0;
}
|
Back to the original code:
1. Integer array, but input uses "%f".
2. Array indexing starts from 0, not 1. If I say that n=3, then the valid indices in your loop are {1,2}, which is not three items. {0,1,2} contains three items.
3. Within the "add 2, if non-negative" loop you do increase the loop counter by 3 on every iteration. The intention is probably to modify array elements, and only those array elements, whose value is non-negative.