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