my code would not work setting it to nullptr for multiple reasons.
first, the key one, is that it dereferences the pointer. You cannot dereference nullptr, it will crash most OS immediately and is always an error.
Second, I started at the first one, not the 0th. The skipped iteration is not significant for performance etc, but it handles edge cases better like negative numbers (so if you set it to zero and they are all negative, you get 0 instead of your largest value!).
my logic says to pick off the first value in the list and update only if it finds one bigger than the first one, else the biggest is the first one by default.
so lets look at it again with comments on those ideas:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
int* maxArrayElement(int arr[])
{
int *largestSoFar = arr; // LSF is now a pointer to the first item in arr, eg 89 in your example.
for (int idx = 1; idx < 10; ++idx) //starts at 1, LSF already looked at and absorbed [0]
{
if (arr[idx] > *largestSoFar) //deref of LSF: * means to go to the value it points to.
//if you init LSF to nullptr, the above line will crash/fail / undefined behavior problems
//even if nullptr worked, it would SKIP the first item and give the wrong result.
largestSoFar = (&(arr[idx]));
}
return largestSoFar;
}
|
you can code around it so you init to nullptr and iterate from zero. Its just more code to do it... you have to put something in like if LSF == nullptr then LSF = pointer to current item else ...
its a topic for another day but the concept of defaulting items to avoid conditions is a good performance tweak at times and it also simplifies code often.
eg instead of
int x{0};
...
if(y == 3) x =10;
else
x = 11;
is much easier to say
int x {11};
if(y==3) x = 10; //else, its 11, you already set it to that. I am using this idea above, though its not as easy to see in the routine.