Found some very bizarre behaviour when trying to brainstorm a problem:
Purpose of code: Simple code to find the largest number in an array. I simply store the first index to a variable and compare it to every other index in the list. If another number is larger, that number replaces the number stored in my variable and the process repeats until the end of the list.
#include <stdio.h>
const int SIZE = 8;
int main(void)
{
int arr[] = {7, 3, 9, 14, 1, 27, 14, 2};
int largest;
largest = arr[0];
for (int i = 1; i <= SIZE; i++)
{
if (largest < arr[i])
{
largest = arr[i];
}
}
printf("The largest number in the array is %i\n", largest);
}
Weird behaviour: This works, sometimes. Other times I get large numbers that give me the impression I've hit an area of memory I shouldn't have. I could understand if this happened every time but because it only happens every 2nd or 3rd time I compile the code I'm bewildered. The code doesn't change and yet the output does
Console Log:
~/pset3/plurality/ $ ./test
The largest number in the array is 1366797536
~/pset3/plurality/ $ ./test
The largest number in the array is 27
~/pset3/plurality/ $ ./test
The largest number in the array is 27
~/pset3/plurality/ $ ./test
The largest number in the array is 1773422672
~/pset3/plurality/ $
My ideas: The loop somehow hits goes past the end of the array and sees that as the largest number. Again the bizarreness of this is that this only happens 50% of the time
Any ideas would be greatly appreciated.