伸缩型数组成员(C99)

作者:追风剑情 发布于:2020-3-10 19:21 分类:C

示例

  1. //Visual Studio中加上这句才可以使用scanf()
  2. //否则只能使用scanf_s()
  3. #define _CRT_SECURE_NO_WARNINGS
  4. #include <stdio.h>
  5. #include <string.h>
  6. #include <ctype.h>
  7. //malloc()、free()
  8. #include <stdlib.h>
  9. #include <time.h>
  10.  
  11. struct flex
  12. {
  13. size_t count;
  14. double average;
  15. //C99新增的一个特性:
  16. //伸缩型数组成员必须是结构的最后一个成员
  17. //结构中必须至少有一个成员
  18. //伸缩数组的声明类似于普通数组,只是它的方括号中是空的
  19. double scores[]; //伸缩型数组成员(flexible array member)
  20. };
  21.  
  22. void showFlex(const struct flex * p);
  23.  
  24. //argc: 参数个数 argv[]: 参数数组
  25. //int main(int argc, char **argv)
  26. int main(int argc, char *argv[])
  27. {
  28. struct flex *pf1, *pf2;
  29. int n = 5;
  30. int i;
  31. int tot = 0;
  32.  
  33. // 为结构和数组分配存储空间
  34. pf1 = malloc(sizeof(struct flex) + n * sizeof(double));
  35. pf1->count = n;
  36. for (i = 0; i < n; i++)
  37. {
  38. pf1->scores[i] = 20.0 - i;
  39. tot += pf1->scores[i];
  40. }
  41. pf1->average = tot / n;
  42. showFlex(pf1);
  43.  
  44. n = 9;
  45. tot = 0;
  46. pf2 = malloc(sizeof(struct flex) + n * sizeof(double));
  47. pf2->count = n;
  48. for (i = 0; i < n; i++)
  49. {
  50. pf2->scores[i] = 20.0 - i / 2.0;
  51. tot += pf2->scores[i];
  52. }
  53. pf2->average = tot / n;
  54. showFlex(pf2);
  55.  
  56. //释放内存
  57. free(pf1);
  58. free(pf2);
  59.  
  60. system("pause");
  61. return 0;
  62. }
  63.  
  64. void showFlex(const struct flex * p)
  65. {
  66. int i;
  67. printf("Scores : ");
  68. for (i = 0; i < p->count; i++)
  69. printf("%g ", p->scores[i]);
  70. printf("\nAverage: %g\n", p->average);
  71. }

运行测试

1111.png

标签: C语言

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号