柔性数组的优点:
1.内存碎片更少,内存利用率更高
2.内存空间连续,访问速度更快
3.使用方法简单,步骤少,不容易出现错误
#include <stdio.h>
#include <stdlib.h>
//在结构体内实现可变数组
//使用柔性数组的方法
struct S
{
int n;
//int arr[];
int arr[0];//未知大小的,柔性数组成员,数组的大小是可调整的
};
int main1()
{
//struct S s;
//printf("%d\n", sizeof(s));//4
struct S* ps = malloc(sizeof(struct S) + 5 * sizeof(int));
ps->n = 100;
int i = 0;
for (i = 0; i < 5; i++)
{
ps->arr[i] = i;
}
struct S* ptr = realloc(ps, 44);
if(ptr!=NULL)
{
ps = ptr;
}
for (i = 5; i < 10; i++)
{
ps->arr[i] = i;
}
for (i = 0; i < 10; i++)
{
printf("%d", ps->arr[i]);
}
free(ps);
ps = NULL;
return 0;
}
//使用普通方法
struct S2
{
int n;
int* ps;
};
int main()
{
struct S2* s2 = malloc(sizeof(struct S2));
s2->ps = malloc(sizeof(int) * 5);
s2->n = 100;
int i = 0;
for (i = 0; i < 5; i++)
{
*((s2->ps)+i) = i;
}
for (i = 0; i < 5; i++)
{
printf("%d ", *((s2->ps) + i));
}
struct S2* ptr = realloc(s2->ps,40);
if (ptr != NULL)
{
s2->ps = ptr;
}
for (i = 5; i < 10; i++)
{
*((s2->ps) + i) = i;
}
for (i = 0; i < 10; i++)
{
printf("%d ", *((s2->ps) + i));
}
free(s2->ps);
free(s2);
s2->ps = NULL;
s2 = NULL;
return 0;
}