11
Appliquer une fonction aux éléments d'un tableau
- #include <stdio.h>
- int inc( int *n ) {
- return ++*n;
- }
- int dec( int *n ) {
- return --*n;
- }
- void apply( int (*f)( int * ), int tab[], int siz ) {
- int *p;
- for( p = tab; p < tab+siz; p++ )
- f( p );
- }
- main() {
- int i;
- int tab[ 10 ];
- for ( i = 0; i < 10; i++ )
- tab[ i ] = i;
- for ( i = 0; i < 10; i++ )
- printf("%d\n", tab[ i ]);
- apply( inc, tab, 10 );
- printf("\n");
- for ( i = 0; i < 10; i++ )
- printf("%d\n", tab[ i ]);
- apply( dec, tab, 10 );
- printf("\n");
- for ( i = 0; i < 10; i++ )
- printf("%d\n", tab[ i ]);
- }
$ gcc -o apply apply.c
$ ./apply
0
1
2
...
1
2
3
...
0
1
2
...
Commentaires