fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. enum VTYPE {VSTRING, VINT, VFLOAT};
  6. typedef enum VTYPE vtype;
  7. struct Value {
  8. vtype typ;
  9. /*
  10.   type=1 ==> get vstring
  11.   type=2 ==> get int
  12.   type=3 ==> get float
  13.   */
  14. union {
  15. char *vstring;
  16. int vint;
  17. float vfloat;
  18. };
  19. };
  20.  
  21. void clear(struct Value* vall){
  22. if (vall->typ == VSTRING){
  23. free(vall->vstring);
  24. }
  25. memset(vall, 0, sizeof(*vall));
  26. }
  27.  
  28. void print_value(struct Value *v)
  29. {
  30. static const char *types[] = {"VSTRING", "VINT", "VFLOAT"};
  31. printf( "ValueType : %s\n", v->typ >= 0 && v->typ < 3 ? types[v->typ] : "ERROR");
  32. if (VSTRING == v->typ) {
  33. printf( "ValueString : %s\n", v->vstring);
  34. }
  35. else if (VINT == v->typ) {
  36. printf( "ValueInt : %d\n", v->vint);
  37. }
  38. else if (VFLOAT == v->typ) {
  39. printf( "ValueFloat : %f\n", v->vfloat);
  40. }
  41. }
  42.  
  43. void copy_value(struct Value *source, struct Value *dest) {
  44. if (VSTRING == source->typ) {
  45. dest->vstring = malloc(strlen(source->vstring) + 1);
  46. strcpy(dest->vstring, source->vstring);
  47. }
  48. else if (VINT == source->typ) {
  49. dest->vint = source->vint;
  50. }
  51. else if (VFLOAT == source->typ) {
  52. dest->vfloat = source->vfloat;
  53. }
  54. dest->typ = source->typ;
  55. }
  56.  
  57. int main()
  58. {
  59. const char *msg = "C Programming/may this a very big utf-8 string!";
  60. struct Value v;
  61. /////////////////////////////////////////////
  62. v.typ=VSTRING;
  63. v.vstring = malloc(strlen(msg) + 1);
  64. strcpy(v.vstring, msg);
  65. print_value(&v);
  66.  
  67.  
  68. struct Value copy;
  69. copy_value(&v, &copy);
  70. print_value(&copy);
  71. clear(&copy);
  72. copy.typ=VINT;
  73. copy.vint=5;
  74. print_value(&copy);
  75.  
  76. clear(&v);
  77. }
  78.  
Success #stdin #stdout 0s 10320KB
stdin
Standard input is empty
stdout
ValueType : VSTRING
ValueString : C Programming/may this a very big utf-8 string!
ValueType : VSTRING
ValueString : C Programming/may this a very big utf-8 string!
ValueType : VINT
ValueInt : 5