Arrays And Functions
Pop Quiz What does this print?
Pop Quiz What does this print?
Array Parameters Array parameters passed as base address Function uses that to find elements
Debugging Need to tell debugger to display parameter as array:
Array Parameters Array parameters always act like passed by reference Modification in function modifies original
Arrays by Ref Declare array as const to prevent changes in function ALWAYS do this if function does not have to modify array!!!
I take the address of an array of exactly 5 integers Size This function is dumb: I take the address of an array of exactly 5 integers
I take the address of any size array of integers This function is broken: I take the address of any size array of integers Crap
Size Parameter Must pass size as second parameter No other way to know
Samples Add up elements in array
Debugger Trick Can make debugger show you "current item"
Samples 10 9 Swap two elements 1 2 3 4 5 6 7 8 Don't need size Modify original array – non const 1 2 3 4 5 6 7 8 10 9
Arrays Can't Be Returned Function can not have return type of array
Arrays Can't Be Returned Solution : take in existing array as non const parameter:
Samples Make a Reversed Copy Const original, non-const empty array
Samples Find smallest value 1 2 3 4 5 6 7 8 10 9
Samples 10 9 Index more powerful than value 1 2 3 4 5 6 7 8 Min value = 4 No easy way to find location Min element is at 7 Can easily get value : array[minLocation] Can manipulate based on location 1 2 3 4 5 6 7 8 10 9
Samples Find index instead of value:
Summary Passing array to function passes memory address Always "by reference" Need to pass in size No returning arrays Take as parameter & change