getMax.c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | /* ポインタで渡した配列の最大値を得る */ #include <stdio.h> void sub( int *p) { int i, max; max = *p; /* 先頭の数をとりあえず最大値として代入 */ for (i=1; i<5; i++){ /* 2番目のデータからチェック */ /* 最大値を検索 */ if (max < *(p+i)){ max = *(p+i); } } printf ( "最大値 = %d\n" , max); } int main( void ) { int a[] = {100, 25, -100, 777, 8}; sub(a); return 0; } |
実行結果
最大値 = 777
こう記述しても同じ
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #include <stdio.h> void sub( int *p) { int i, max; max = p[0]; /* 先頭の数をとりあえず最大値として代入 */ for (i=1; i<5; i++){ /* 2番目のデータからチェック */ /* 最大値を検索 */ if (max < p[i]){ max = p[i]; } } printf ( "最大値 = %d\n" , max); } int main( void ) { int a[] = {100, 25, -100, 777, 8}; sub(a); return 0; } |
コメント