As already said in other comments you are missing in the famous "off-by-one", IE, you are accessing a position outside of your array.
When we declare arrays
, what is placed between brackets is the size of the array, not the final index you want.
That is to say:
int numeros[10];
Creates the array called numeros
that can store only 10 ints, so the indexes range from 0 to 9.
Their laços for
iteram from 0 to 10, then you are accessing 11 positions and not 10 and therefore accessing a position outside the array.
Now the second part of the error is due to how you are trying to apply the proposed algorithm and this subdivides into 2 errors:
- According to the proposed algorithm, you need to go through the
array once to change the values that are
<= 0
and another for
out of that to then print the result, but you did 2 laços for
nested...
- Besides having the
2 laços for aninhados
, you used the same
control variable in 2. Then when the second is over, i has
value 11 then when the first goes will check if i <= 10, as
i is 11 he does not perform.
Arranging the code to assign the 1 correctly and without extrapolating the limit of the array is like this:
for( i = 0; i < 10; ++i )
{
if( X[i] <= 0 )
{
X[i] = 1;
}
}
Now just do the laço for
of impression after that laço for
fully execute.
Your third is (impression of the resulting vector) is within the second when it should be after the end of the second (test and replace all negatives).
– anonimo
Also remembering that if your array has size 10, the indices of this array will be between 0 and 9, not between 0 and 10 as in your code. Allocating a value at position 10 may not generate an immediate error, but you will be allocating a value in a memory space that does not belong to the array, and may even overwrite a value being used by another part of the program.
– Andre