#include <stdio.h> void maxminvalue(int b[], int n); /*propotype*/ int max, min;/*define global variables*/ void main() { int i, a[] = {21,34,11,45,89,26,87,39,63,50}, n; n = sizeof(a)/sizeof(a[0]); maxminvalue(a, n); /*call function*/ printf("min=%d, max=%d\n",min,max); } void maxminvalue(int b[], int n) { int i; max=min=b[0]; /*initialization*/ for (i = 1; i < n; i++) { if (b[i] < min) min = b[i]; else if(b[i] > max) max = b[i]; } }
第二種實現形式——形參是指針,實參是數組名:數組
#include <stdio.h> void maxminvalue(int *b, int n);/*propotypes*/ int max, min; void main() { int i, a[] = {21,34,11,45,89,26,87,39,63,50}, n; n = sizeof(a)/sizeof(a[0]); maxminvalue(a,n); /*call function, actual paraments is array name*/ printf("min = %d, max = %d\n",min,max); } void maxminvalue(int *b, int n) { int i; int *p, *end = b+n; max = min = *b; for(p = b+1; p < end; p++) { if (*p < min) min = *p; else if(*p > min) max = *p; }
第三種:形參是指針,實參也是指針:指針
#include <stdio.h> void maxminvalue(int *b, int n);/*propotypes*/ int max, min; void main() { int i, a[] = {21,34,11,45,89,26,87,39,63,50}, n; int *p = a; n = sizeof(a)/sizeof(a[0]); maxminvalue(p,n); printf("min = %d, max = %d\n",min,max); } void maxminvalue(int *b, int n) { int i; int *p, *end = b+n; max = min = *b; for(p = b+1; p < end; p++) { if (*p < min) min = *p; else if(*p > min) max = *p; } }