fork download
  1. #include <stdint.h>
  2. #include <stdio.h>
  3. #include <stddef.h>
  4.  
  5. struct threshold_t {
  6. uint8_t upper;
  7. uint8_t lower;
  8. };
  9.  
  10. struct threshold_abc_t {
  11. struct threshold_t a;
  12. struct threshold_t b;
  13. struct threshold_t c;
  14. };
  15.  
  16. static void print(const struct threshold_abc_t * const thresholds) {
  17. printf("{\"a\": {\"lower\": %u, \"upper\": %u},\n"
  18. " \"b\": {\"lower\": %u, \"upper\": %u},\n"
  19. " \"c\": {\"lower\": %u, \"upper\": %u}}\n",
  20. thresholds->a.lower, thresholds->a.upper,
  21. thresholds->b.lower, thresholds->b.upper,
  22. thresholds->c.lower, thresholds->c.upper);
  23. }
  24.  
  25. static void set_thresholds_0(struct threshold_t * const threshold,
  26. const uint8_t lower, const uint8_t upper) {
  27. threshold->lower = lower;
  28. threshold->upper = upper;
  29. }
  30.  
  31. enum threshold {
  32. THRESHOLD_A = offsetof(struct threshold_abc_t, a),
  33. THRESHOLD_B = offsetof(struct threshold_abc_t, b),
  34. THRESHOLD_C = offsetof(struct threshold_abc_t, c),
  35. };
  36.  
  37. static void set_thresholds_1(struct threshold_abc_t * const thresholds,
  38. const enum threshold selection, const uint8_t lower, const uint8_t upper) {
  39. struct threshold_t * const threshold =
  40. (struct threshold_t * const)(&((uint8_t * const)thresholds)[selection]);
  41. threshold->lower = lower;
  42. threshold->upper = upper;
  43. }
  44.  
  45. int main() {
  46. struct threshold_abc_t thresholds = {
  47. .a = {
  48. .lower = 5,
  49. .upper = 15,
  50. },
  51. .b = {
  52. .lower = 0,
  53. .upper = 20,
  54. },
  55. .c = {
  56. .lower = 0,
  57. .upper = 30,
  58. }
  59. };
  60. print(&thresholds);
  61. set_thresholds_0(&thresholds.a, 2, 50);
  62. print(&thresholds);
  63. set_thresholds_1(&thresholds, THRESHOLD_C, 69, 99);
  64. print(&thresholds);
  65. return 0;
  66. }
Success #stdin #stdout 0s 1788KB
stdin
Standard input is empty
stdout
{"a": {"lower": 5, "upper": 15},
 "b": {"lower": 0, "upper": 20},
 "c": {"lower": 0, "upper": 30}}
{"a": {"lower": 2, "upper": 50},
 "b": {"lower": 0, "upper": 20},
 "c": {"lower": 0, "upper": 30}}
{"a": {"lower": 2, "upper": 50},
 "b": {"lower": 0, "upper": 20},
 "c": {"lower": 69, "upper": 99}}