I try to iterate an array of numbers from 1 to 10 in C++, I succeed but in the end a negative number is executed. Why is this? because I don't get any compile error. Here I leave the code:
#include <iostream>
using namespace std;
int main() {
int numeros[10] = {1,2,3,4,5,6,7,8,9,10};
for(int i=0; i<=10; i++) {
cout<<numeros[i]<<endl;
}
return 0;
}
When array is used in any language, or at least in many of these (C, C++, C#, Java, Javascript, php, python, VB, among others) they must be traversed from position 0 to position size -1 .
In your case the size is 10, which is why you should loop through it only up to position 9 , which is equal to size-1 (10-1=9) .
So your error is in the condition of your
for
:i<=10
, which causes i to cause a stack overflow when applyingcout<<numeros[10]<<endl;
position that is not reserved within your numbers variable , which is why in the end it prints a negative or rather a memory address since that is what it prints.Solution:
If you notice just change the i<=10 to i<10 .