6

Apply a function to the elements of a table

  1. #include <stdio.h>
  2.  
  3. int inc( int *n ) {
  4.     return ++*n;
  5. }
  6.  
  7. int dec( int *n ) {
  8.     return --*n;
  9. }
  10.  
  11. void apply( int (*f)( int * ), int tab[], int siz ) {
  12.     int *p;
  13.  
  14.     for( p = tab; p < tab+siz; p++ )
  15.         f( p );
  16. }
  17.  
  18. main() {
  19.     int i;
  20.  
  21.     int tab[ 10 ];
  22.  
  23.     for ( i = 0; i < 10; i++ )
  24.         tab[ i ] = i;
  25.  
  26.     for ( i = 0; i < 10; i++ )
  27.         printf("%d\n", tab[ i ]);
  28.  
  29.     apply( inc, tab, 10 );
  30.  
  31.     printf("\n");
  32.     for ( i = 0; i < 10; i++ )
  33.         printf("%d\n", tab[ i ]);
  34.  
  35.     apply( dec, tab, 10 );
  36.     printf("\n");
  37.     for ( i = 0; i < 10; i++ )
  38.         printf("%d\n", tab[ i ]);
  39. }
$ gcc -o apply apply.c
$ ./apply
0
1
2
...

1
2
3
...

0
1
2
...

Comments

Your comment:
[p] [b] [i] [u] [s] [quote] [pre] [br] [code] [url] [email] strip help 2000

Enter a maximum of 2000 characters.
Improve the presentation of your text with the following formatting tags:
[p]paragraph[/p], [b]bold[/b], [i]italics[/i], [u]underline[/u], [s]strike[/s], [quote]citation[/quote], [pre]as is[/pre], [br]line break,
[url]http://www.izend.org[/url], [url=http://www.izend.org]site[/url], [email]izend@izend.org[/email], [email=izend@izend.org]izend[/email],
[code]command[/code], [code=language]source code in c, java, php, html, javascript, xml, css, sql, bash, dos, make, etc.[/code].