Linux下的c程序---数组、malloc #include <stdio.h>
#include <stdlib.h>
struct flex
{
int count;
double average;
double scores[];  // 定义可伸缩的数组
}; // 声明结构体
void showFlex(const struct flex * p);  //定义函数
sizeof结构体大小int main(void)
{
struct flex * pf1, *pf2;
int n = 5;  // 变量的初始化
int i;
int tot = 0;
// allocate space for structure plus array
pf1 = malloc(sizeof(struct flex) + n * sizeof(double)); //根据数组的⼤⼩申请地址空间
pf1->count = n;
for (i = 0; i < n; i++)
{
pf1->scores[i] = 20.0 - i;  //给数组元素赋值
tot += pf1->scores[i];
}
pf1->average = tot / n;
showFlex(pf1);
n = 9;
tot = 0;
pf2 = malloc(sizeof(struct flex) + n * sizeof(double));
pf2->count = n;
for (i = 0; i < n; i++)
{
pf2->scores[i] = 20.0 - i/2.0;
tot += pf2->scores[i];
}
pf2->average = tot / n;
showFlex(pf2);
free(pf1); //释放地址空间
free(pf2);
return 0;
}
void showFlex(const struct flex * p)  //遍历结构体中的数组并打印平均值
{
int i;
printf("Scores : ");
for (i = 0; i < p->count; i++)
printf("%g ", p->scores[i]);
printf("\nAverage: %g\n", p->average);
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。