fork download
  1. #include <stdio.h>
  2.  
  3. /* eigener Testtyp (neben double und string s.u.) */
  4. typedef struct {
  5. char name[20];
  6. int alter;
  7. char geschlecht;
  8. } Person;
  9.  
  10. /* Aktionen für jeden Typ */
  11. void f_double(double*d) { printf("%f\n",*d); }
  12. void f_string(char*d) { puts(d); }
  13. void f_struct(Person*d) { printf("%s %d %c\n",d->name,d->alter,d->geschlecht); }
  14.  
  15. /* anonymer Stackelement-Typ */
  16. typedef struct {
  17. void (*f)();
  18. void *d;
  19. } Eintrag;
  20.  
  21. /* Aktionen für den Stack */
  22. enum{PUSH,POP,PRINTALL};
  23.  
  24. /* unser Stack-Typ */
  25. typedef struct{
  26. Eintrag (*work)();
  27. int i;
  28. Eintrag eintrag[100];
  29. } Stack;
  30.  
  31. #define CALL(x) x.f(x.d)
  32. #define doublePUSH(s,p) s.work(&s,PUSH,p,f_double)
  33. #define stringPUSH(s,p) s.work(&s,PUSH,p,f_string)
  34. #define structPUSH(s,p) s.work(&s,PUSH,p,f_struct)
  35. #define DOStack(s,e) s.work(&s,e)
  36.  
  37. /* alle Stackoperationen in einer Funktion zusammengefasst */
  38. Eintrag work(Stack *this,int e,void*p,void(*f)())
  39. {
  40. switch(e){
  41. case POP: return this->eintrag[--this->i];
  42. case PUSH: { Eintrag e={f,p}; this->eintrag[this->i++]=e;break; }
  43. case PRINTALL: { int i=this->i; while(i--) CALL(this->eintrag[i]);}
  44. }
  45. }
  46.  
  47. int main()
  48. {
  49. int i;
  50. Eintrag eintrag;
  51.  
  52. /* Testdaten mit 3 unterschiedlichen Typen bereitstellen */
  53. double d[]={1,2,3};
  54. char *s[]={"s1","s2","s3"};
  55. Person p[]={{"schmidt",47,'m'},{"meier",11,'w'},{"lehmann",12,'m'}};
  56.  
  57. /* unser Stack-Objekt */
  58. Stack stack={work};
  59.  
  60. /* Testdaten mit ihren unterschiedlichen Typen in EINEN Stack packen (eigentliche Aufgabe) */
  61. for(i=0;i<3;++i)
  62. doublePUSH(stack,&d[i]),stringPUSH(stack,s[i]),structPUSH(stack,&p[i]);
  63.  
  64. /* Kontrollausgabe: gesamter Stackinhalt */
  65. DOStack(stack,PRINTALL);
  66.  
  67. /* Stack einzeln wieder abräumen und dabei jedes Element nochmal kontrollausgeben */
  68. for(i=0;i<9;++i)
  69. eintrag=DOStack(stack,POP),CALL(eintrag);
  70.  
  71. return 0;
  72. }
  73.  
Success #stdin #stdout 0s 1832KB
stdin
Standard input is empty
stdout
lehmann 12 m
s3
3.000000
meier 11 w
s2
2.000000
schmidt 47 m
s1
1.000000
lehmann 12 m
s3
3.000000
meier 11 w
s2
2.000000
schmidt 47 m
s1
1.000000