### How do I use arrays?

I've been reading the tutorial for arrays. From what I got, this code ` int num [5] {1, 2, 3, 4, 5} ` is supposed to output 1 2 3 4 5. I'm not sure if I'm missing something or I'm reading it incorrectly. So, my code looks like this:
 ``123456789101112`` ``````#include using namespace std; int main() { int num[10] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; cout << num[10]; return 0; }``````

It's outputting -858993460. Should it not output 0 1 2 3 4 5 6 7 8 9? I thought it would output the numbers inside the bracket. What am I not understanding?
 ``123456789101112`` ``````#include int main() { const int N = 10 ; const int num[N] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } ; // num[0] == 0, num[1] == 1, ... upto num[N-1] == 9 // the array num has N elements; the first is num[0], and the last is num[N-1] for( int i = 0 ; i < N ; ++i ) std::cout << num[i] << ' ' ; std::cout << '\n' ; }``````
array[n] will give the nth element in the array.
If you have an array:
 `` `` ``int num[5] = {2, 4, 6, 8, 10};``

Then doing `cout << num[5];` will be an error because array index starts from '0' and ends at n-1. So in this case n = 5 and the last index of the array is 4 (5-1). To access 10, you'd do `cout << num[4];`. To print out all the elements of an array, you need a loop, which JLBorges has already shown you.
The number you are seeing there num[10] is the last value that was held in that memory address. There are no bounds checks on the array. I.e you can step over (buffer overflow) and this is a good place where bugs can happen.

Better off using vectors for arrays.
Topic archived. No new replies allowed.