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