C99中结构体最后一个成员允许一个大小未知的数组
sizeof 返回的这种结构大小不包括柔性数组的内存
struct s
{int n; int arr[];//柔性数组成员
};
int main()
{int sz = sizeof(struct s);printf("%d\n", sz); //4return 0;
}
包含柔性数组成员的结构用malloc ()函数进行内存的动态分配,并且分配的内存应该大于结构的大 小,以适应柔性数组的预期大小。
两种实现,推荐第一种
第一种
struct s* ps = (struct s*)malloc(sizeof(struct s) + 40);if (ps == NULL)return 1;ps->n == 100;int i = 0;for (i = 0; i < 10; i++){ps->arr[i] = i;}for (i = 0; i < 10; i++){printf("%d ", ps->arr[i]);}struct s* ptr = realloc(ps, sizeof(struct s) + 80);if (ptr != NULL){ps = ptr;}free(ps);ps = NULL;
第二种
struct s
{int n;int* arr;
};
int main()
{struct s* ps = (struct s*)malloc(sizeof(struct s));if (ps == NULL)return 1;ps->n = 100;ps->arr = (int*)malloc(40);if (ps->arr == NULL)return 1;int i = 0;for (i = 0; i < 10; i++){ps->arr[i] = i;}for (i = 0; i < 10; i++){printf("%d ", ps->arr[i]);}//扩容int* ptr = (int*)realloc(ps->arr,80);if (ptr == NULL)return 1;elseps = ptr;//释放free(ps->arr);free(ps);ps = NULL;return 0;
}