1
0

flexmemb.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // flexmemb.c -- flexible array member (C99 feature)
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. struct flex
  5. {
  6. size_t count;
  7. double average;
  8. double scores[]; // flexible array member
  9. };
  10. void showFlex(const struct flex * p);
  11. int main(void)
  12. {
  13. struct flex * pf1, *pf2;
  14. int n = 5;
  15. int i;
  16. int tot = 0;
  17. // allocate space for structure plus array
  18. pf1 = malloc(sizeof(struct flex) + n * sizeof(double));
  19. pf1->count = n;
  20. for (i = 0; i < n; i++)
  21. {
  22. pf1->scores[i] = 20.0 - i;
  23. tot += pf1->scores[i];
  24. }
  25. pf1->average = tot / n;
  26. showFlex(pf1);
  27. n = 9;
  28. tot = 0;
  29. pf2 = malloc(sizeof(struct flex) + n * sizeof(double));
  30. pf2->count = n;
  31. for (i = 0; i < n; i++)
  32. {
  33. pf2->scores[i] = 20.0 - i/2.0;
  34. tot += pf2->scores[i];
  35. }
  36. pf2->average = tot / n;
  37. showFlex(pf2);
  38. free(pf1);
  39. free(pf2);
  40. return 0;
  41. }
  42. void showFlex(const struct flex * p)
  43. {
  44. int i;
  45. printf("Scores : ");
  46. for (i = 0; i < p->count; i++)
  47. printf("%g ", p->scores[i]);
  48. printf("\nAverage: %g\n", p->average);
  49. }