fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct thing {
  5. int part1;
  6. double *part2;
  7. };
  8.  
  9. struct thing *setValue (struct thing *t, int pos, double set){
  10. if (t->part1 < pos){ // check to see if array is large enough
  11. t->part2 = realloc (t->part2, (pos+1) * sizeof(double)); /* assume no error */
  12. for (int a = t->part1 + 1; a < pos + 1; a++)
  13. t->part2[a] = 0;
  14. t->part1 = pos;
  15. }
  16. t->part2[pos] = set; // ALWAYS stores an integer, don't know why
  17. return t;
  18. }
  19.  
  20. int main(void) {
  21. struct thing *abc;
  22. abc = malloc(sizeof(struct thing)); /* assume no error */
  23. abc->part1 = 0;
  24. abc->part2 = malloc(sizeof(double)); /* assume no error */
  25. setValue(abc, 42, 4.2);
  26. setValue(abc, 4, -0.04);
  27. printf("abc's values: %f and %f\n", abc->part2[4], abc->part2[42]);
  28. return 0;
  29. }
Success #stdin #stdout 0.02s 1808KB
stdin
Standard input is empty
stdout
abc's values: -0.040000 and 4.200000