+ 1
Arrays and memory Question
If we are given int array[5]; and we have not given any values to array[0] to array[5], what values are held in each place? And I read somewhere that the size of array cannot be 5 itself, why should it be until 4 if we are assuming 5 numbers exist for each index? I believe it is due to the fact that index (i) starts from 0 and not 1, so this might be the reason. Please share your opinion. Thanks.
5 Answers
+ 8
For empty integer arrays, I think the default values would be stray/junk values. Similar to uninitialised integer variables.
If you do:
int array[5];
You are declaring int array of size 5, with index 0, 1, 2, 3 and 4.
+ 8
@Kourosh trying to access array[5] will result in runtime error, since it's out of bound and the compiler doesn't check it.
Negative indexes aren't supported in C++, but is supported in Ruby I think.
+ 2
So you mean at index 5, nothing exists ? or is it garbage values ?
Also is it possible to have negative indexes @Hasty Rei?
+ 2
@Hasty and @Nick, thank you for your explanation, It was helpful!
+ 1
I might be wrong on what values are held. but when you initiate a new array it picks some values in memory that it could fit. and any value that was stored there before but was deallocated would be the current value.
int array[5]; does have 5 values but like you said it starts at 0.
if you go
int array1[5];
int array2[5];
array1[5] =24;
the value would get saved to array2[0]
which I think is considered a memory leak. if you need to have arrays of varying length use containers from the STL library