Reputation: 11
I have the following code:
void generate_random_array(int8_t array[], int array_size){
srand(time(NULL));
for(int i = 0; i < array_size + 1; i++){
array[i] = rand() % 21 + (-10);
printf("%d, %d\n", array[i], i);
}
}
int main(){
int8_t some_array[100];
generate_random_array(some_array, 100);
for(int i = 0; i < 101; i++){
printf("%d %d\n", some_array[i], i);
}
return 0;
}
The program generates random elements of a given array in the range from -10 to 10 and then it displays them. The problem is that the last element of an array changes to 100 when I print elements the second time. I would like to know why.
Upvotes: 1
Views: 99
Reputation: 2067
In your function generate_random_array
you are iterating the i
upto array_size + 1
. And you have declared an array of size 100
; int8_t some_array[100];
OS will reserve the 100*sizeof(int8_t)
bytes memory for you.
Indexes of your array would be lying in range [0,100) ie. excluding the 100th
location.
Now, what you are doing is that you modifying the some_array[100]
which you have not claimed in your declaration. Its being possible because C
doesn't do any out-of-bound access checking.
But key point to note is that you are trying to modifying/reading the unclaimed memory. So this is undetermined behavior. It might be possible that you might get different value other than 100
, sometimes.
But all story short, this behavior is undetermined because you are accessing the out-of-bound index of array.
Upvotes: 1
Reputation: 4945
Indexing of an array starts at zero.
int array[3];// an int array with 3 elements
array[0]; //first element
array[1]; //second element
array[2]; //third element
array[3]; //undefined because it is beyond the end of the array
Upvotes: 3