fork(3) download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <time.h>
  5.  
  6. union members {
  7. int *intp;
  8. char *charp;
  9. double doublev;
  10. };
  11. struct group {
  12. int lastunionmember;
  13. union members x;
  14. };
  15.  
  16. struct group f1(void) {
  17. struct group r = {0};
  18. int choice = rand() % 3;
  19.  
  20. if (choice == 0) {
  21. r.x.intp = malloc(sizeof (int)); // remember to free(intp) at some time
  22. *r.x.intp = 42;
  23. r.lastunionmember = 1;
  24. }
  25. if (choice == 1) {
  26. r.x.charp = malloc(42); // remember to free(charp) at some time
  27. strcpy(r.x.charp, "forty two");
  28. r.lastunionmember = 2;
  29. }
  30. if (choice == 2) {
  31. r.x.doublev = 3.14159;
  32. r.lastunionmember = 3;
  33. }
  34. return r;
  35. }
  36.  
  37. int main(void) {
  38. struct group x;
  39. srand(time(0));
  40. for (int k = 0; k < 20; k++) {
  41. x = f1();
  42. switch (x.lastunionmember) {
  43. default: printf("invalid value\n"); break;
  44. case 1: printf("int value is %d\n", *x.x.intp); break;
  45. case 2: printf("string is \"%s\"\n", x.x.charp); break;
  46. case 3: printf("double value is %f\n", x.x.doublev); break;
  47. }
  48. }
  49. }
  50.  
Success #stdin #stdout 0s 2292KB
stdin
Standard input is empty
stdout
string is "forty two"
string is "forty two"
string is "forty two"
string is "forty two"
int value is 42
string is "forty two"
double value is 3.141590
int value is 42
string is "forty two"
int value is 42
int value is 42
int value is 42
double value is 3.141590
double value is 3.141590
int value is 42
string is "forty two"
string is "forty two"
string is "forty two"
int value is 42
string is "forty two"