I’ve just started learning C++ so I’m fairly sure the answer may be a simple one. As a test I’m just setting up an array and then wanting to print out the array by looping through it.
My code is below. It prints out my array as expected but then prints out a load of other numbers below it. What are these numbers and where are they coming from? I suspect that ‘sizeof’ isn’t the best to use. All of the examples i’ve found are alot more complicated than I need. In any case I am interested to understand the extra numbers. Any insight available?
int age[4];
age[0]=23;
age[1]=34;
age[2]=65;
age[3]=74;
for (int i = 0; i <= sizeof(age); i++)
cout << age[i] << endl;
return 0;
…output:
23
34
65
74
4
2147307520
0
2293608
4198582
1
3084992
3085608
-1
2293592
1980179637
-725187705
-2
sizeofgives the size of an object in bytes. If the array elements are larger than one byte (asintusually is), the number will be larger than the array size.One way to get the number of elements in an array is to divide by the size of an element:
(note that you also need
<rather than<=, or you’ll still step off the end).Another way is to pass a reference to the array to a function template, instantiated for the array size:
Yet another way is to use a
std::vectororstd::arrayinstead of a plain array: