fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. struct my_type_t {
  5. int x;
  6. int y;
  7. int z;
  8. };
  9.  
  10. struct my_array_t {
  11. struct my_type_t test;
  12. int otherstuff;
  13. };
  14.  
  15. #define GET_STRUCT_OFFSET(st, m) ((size_t) ( (char *)&((st *)(0))->m - (char *)0 ))
  16. #define FIELD_SIZEOF(t, f) (sizeof(((t*)0)->f))
  17.  
  18. void somefunction(struct my_array_t *arrayofstructs, size_t offset, int value) {
  19. int i;
  20. for (i = 0; i < 5; i++) {
  21. //Unfortunatly can't do straight assignment not an lvalue
  22. //if you just want to use the member as a rvalue and not assign can do so normally
  23. memcpy((((void *)&arrayofstructs[i].test) + offset), &value, sizeof(value));
  24. }
  25. }
  26. int main(void) {
  27. struct my_array_t arrayofstructs[5];
  28. somefunction(arrayofstructs, GET_STRUCT_OFFSET(struct my_type_t, x), 1);
  29. somefunction(arrayofstructs, GET_STRUCT_OFFSET(struct my_type_t, y), 2);
  30. somefunction(arrayofstructs, GET_STRUCT_OFFSET(struct my_type_t, z), 3);
  31.  
  32. int i;
  33. for(i = 0; i<5; i++) {
  34. printf("Struct %d: X = %d, Y = %d, Z = %d\n",i,arrayofstructs[i].test.x \
  35. ,arrayofstructs[i].test.y \
  36. ,arrayofstructs[i].test.z);
  37. }
  38.  
  39. return 0;
  40. }
  41.  
  42.  
Success #stdin #stdout 0s 1832KB
stdin
Standard input is empty
stdout
Struct 0: X = 1, Y = 2, Z = 3
Struct 1: X = 1, Y = 2, Z = 3
Struct 2: X = 1, Y = 2, Z = 3
Struct 3: X = 1, Y = 2, Z = 3
Struct 4: X = 1, Y = 2, Z = 3