//柔性数组的使用
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
struct s
{
int i;
int a[];
};
int main()
{
struct s* ps = (struct s*)malloc(sizeof(struct s) + 20 * sizeof(int));
if (ps == NULL)
{
perror("malloc");
return 1;
}
//使用这块空间
ps->i = 100;
int j = 0;
for (j = 0; j < 20; j++)
{
ps->a[j] = j + 1;
}
//调整ps指向空间的大小
struct s* str = (struct s*)realloc(ps, sizeof(struct s) + 40 * sizeof(int));
if (str != NULL)
{
ps = str;
str = NULL;
}
//使用空间后面开辟的40个字节,打印出来
for (j = 0; j < 40; j++)
{
ps->a[j] = j + 1;
}
for (j = 0; j < 40; j++)
{
if (j % 10 == 0)
{
printf("\n");
}
printf("%d ", ps->a[j]);
}
//释放空间
free(ps);
ps = NULL;
return 0;
}
输出结果: