File: Stare vježbe/vjezbe10/67__pfunkcije_genericko_zbrajanje.c

  1. /*
  2.   67__pfunkcije_genericko_zbrajanje.c
  3.   Primjena pointera na funkciju za implementaciju genericke funkcije za
  4.   zbrajanje razlicitih tipova podataka.
  5. */
  6.  
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <malloc.h>
  10. #include <string.h>
  11.  
  12. int int_zbroj(int, int);
  13. char* string_zbroj(char*, char*);
  14.  
  15. void* zbroji(void *a, void *b, void* (*f)(void*, void*)) {
  16. return (*f)(a, b);
  17. }
  18.  
  19. main() {
  20. char s1[]="Tom", s2[]="Jerry";
  21. int a=36, b=64;
  22. int izbroj;
  23. char* szbroj;
  24.  
  25. /* cast parametara u one koje funkcija zbroji ocekuje */
  26. izbroj = (int)zbroji((void*)a, (void*)b,
  27. (void* (*)(void*, void*))int_zbroj);
  28. printf("%d + %d -> %d\n", a, b, izbroj);
  29.  
  30. szbroj = (char*)zbroji((void*)s1, (void*)s2,
  31. (void* (*)(void*, void*))string_zbroj);
  32. printf("%s + %s -> %s\n", s1, s2, szbroj);
  33.  
  34. free(szbroj);
  35.  
  36. return 0;
  37. }
  38.  
  39. int int_zbroj(int a, int b) {
  40. return a+b;
  41. }
  42.  
  43. char* string_zbroj(char *a, char *b) {
  44. char* c = (char*) malloc(strlen(a) + strlen(b) + 4);
  45. strcpy(c, a);
  46. strcat(c, " i ");
  47. strcat(c, b);
  48. return c;
  49. }
  50.