/** In this exampole, we are looking at the different ways we can pass arrays to functions. To compile: gcc -o 05-maxarrays 05-maxarrays.c -Wall To run: ./05-maxarrays C. Andrews 2016-02-22 */ #include #include /* The first approach is to put a sized array in. This is not great unless you want to communicate in your code that this only deals with one array size. AS we showed in class, the compiler typically doesn't enforce this, and you can get strange answers when you pass in arrays that are either longer or shorter than this number. */ int max1(int a[5]){ int max = a[0]; for (int i = 1; i < 5; i++){ if (max < a[i]){ max = a[i]; } } return max; } /* The second approach is to declare it as an array, but pass the length in a separate variable. */ int max2(int a[], int length){ int max = a[0]; for (int i = 1; i < length; i++){ if (max < a[i]){ max = a[i]; } } return max; } /* It is also perfectly reasonable to pass a pointer and the length. This is functionally the same, but not as communicative. */ int max3(int * a, int length){ int max = a[0]; for (int i = 1; i < length; i++){ if (max < a[i]){ max = a[i]; } } return max; } /* This gerneates a random array and then calls the three max functions on it. */ int main(int argc, char * argv[]){ int length = 25; int a[length]; for (int i = 0; i < length; i++){ a[i] = rand() % 25; printf("%d\n", a[i]); } printf("max1: %d\n", max1(a)); printf("max2: %d\n", max2(a, length)); printf("max3: %d\n", max3(a, length)); return 0; }