struct S
{
int a;
char arr[];//柔性数组
};
int main()
{
printf("%d\n",sizeof(struct));//4
//计算结构体的大小时,忽略柔性数组便可,就只看本题中的int便可
return 0;
}数组
struct B
{
int a;
char arr[0];
};
void test2
{
struct Bps = (struct B)malloc(sizeof(struct B));
ps->arr = (char*)malloc(100sizeof(char));
ps->a = 20;
strcpy(ps->arr,“abcdef”);
ptr = realloc(ps,sizeof(struct S)+200sizeof(char));//柔性数组的体现
if(ptr != NULL)
{
ps = ptr;
}//增容
free(ps->arr);//先释放arr,在释放ps
pa->arr = NULL;
free(ps);
ps = NULL;
}ide
struct S
{
int a;
char arr[0];//柔性数组
};
void test1()
{
charptr = NULL;
struct Sps = (struct S*)malloc(sizeof(struct S)+100sizeof(char));//记得强制类型转换
ps->a = 20;
strcpy(ps->arr,“abcdef”);//这儿必定得用strcpy
printf("%d\n",pa->a);
printf("%s\n",ps->arr);
//当arr不够用时
ptr = realloc(ps,sizeof(struct S)+200sizeof(char));//柔性数组的体现
if(ptr != NULL)
{
ps = ptr;
}
free(ps);
ps = NULL;
return 0;
}
int main()
{
test1();
test2();
return 0;
}内存
1.方便内存释放
2.有利于访问速度
3.防止内存碎片it