*简介

伸缩数组(flexible array)这是C99对结构体功能的扩展.可伸缩性的体现在于,在结构体的原型声明时,可以声明一个没有指定数组长度的数组,在使用时通过malloc动态决定结构体变量的数组大小.

*规则

---伸缩数据必须是结构体的最后一个成员

编译报错:"error: flexible array member not at end of struct"

---结构体至少还有一个其他成员

编译报错:"error: flexible array member in otherwise empty struct"

---伸缩数组的声明方式,形如char name[],即方括号没有内容

*示例

#include <stdio.h>
#include <stdlib.h>

struct flexarr{
  int count;
  double sum;
  double avrg;
  double value[];   //flexible array
};

void average(struct flexarr *);

int main(void){
  struct flexarr *fa;   //声明结构体指针
  int n = 6;
  int i;

  fa = malloc(sizeof(struct flexarr)+n*sizeof(double));     //分配内存
  fa->count = n;
  for(i=0;i<n;i++){
	printf("value%d:___\b\b\b",i+1);
	scanf("%lf",&(fa->value[i]));   //赋值
  }

  average(fa);  //求平均数
  printf("The average is: %f\n",fa->avrg);
  free(fa);

  return 0;
}

void average(struct flexarr *ptr){
  int i;
  double sum = 0;

  for(i=0;i<ptr->count;i++){
	sum += ptr->value[i];
  }
  
  ptr->sum = sum;
  ptr->avrg = sum / ptr->count;
}

相关文章:

  • 2022-12-23
  • 2022-02-21
  • 2021-08-26
  • 2022-12-23
  • 2022-12-23
  • 2021-11-26
  • 2021-12-13
猜你喜欢
  • 2022-12-23
  • 2021-10-09
  • 2021-10-22
  • 2021-11-30
  • 2021-11-09
相关资源
相似解决方案