C语言之柔性数组
什么是柔性数组?
C99 中,结构体中的最后一个元素允许是未知大小的数组,这就叫做『柔性数组』成员。
说白了,柔性数组是数组。只不过这是一种特殊的数组——先给出数组大小,然后再根据给出的大小定义柔性数组的大小(用多大就开多大)。
定义柔性数组
定义柔性数组存在于结构体的内部,并不像C++那样直接在数组里填一个变量。柔性数组的定义必须借助结构体实现,例如:
typedef struct st_type
{
int i;
int a[0];//柔性数组成员
}type_a;
有些编译器会报错⽆法编译可以改成:
typedef struct st_type
{
int i;
int a[];//柔性数组成员
}type_a;
柔性数组的特点
- 结构中的柔性数组成员前面必须有至少一个其他成员
- sizeof 返回的这种结构大小不包括柔性数组的内存
- 包含柔性数组成员的结构体用malloc()函数进行内存的动态分配,并且分配的内存应该大于结构体的大小,以适应柔性数组的预期大小。
- 若要改变柔性数组的大小,可以采用realloc()函数重新调整大小。
例如:
typedef struct st_type
{
int i;
int a[0];//柔性数组成员
}type_a;
printf("%d\n", sizeof(type_a));//输出的是4
int i = 0;
type_a *p = (type_a*)malloc(sizeof(type_a)+100*sizeof(int));
//业务处理
p->i = 100;
for(i=0; i<100; i++)
{
p->a[i] = i;
}
free(p);
真·例子
以下代码是用柔性数组做的练习:构建一个动态变化的通讯录 (本例主要是为了练习使用柔性数组,所以只写了通讯录的增添和排序,改、查、删等有空了再写)
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
struct People
{
char name[10];
char sex[5];
int age;
char phone[11];
char addr[30];
};
struct Peoples
{
int i;
struct People contact[];
};
void add_contact(struct Peoples *contacts)
{
struct Peoples * cache;
char buffer;
while (1)
{
printf("是否添加联系人->(y/n): ");
scanf("%c", &buffer);
if (buffer == 'Y' || buffer == 'y')
{
int count;
while( (buffer=getchar()) != '\n' && buffer != EOF); //清除键盘输入的缓冲区
printf("添加格式:name sex age phone addr\n");
count = contacts->i;
contacts->i += 1;
cache = realloc(contacts, sizeof(struct Peoples) + (contacts->i)*sizeof(struct People));
if (cache != NULL)
{
contacts = cache;
// 从下标为0开始存联系人
scanf("%s%s%d%s%s", contacts->contact[count].name, contacts->contact[count].sex, &(contacts->contact[count].age), contacts->contact[count].phone, contacts->contact[count].addr);
while( (buffer=getchar()) != '\n' && buffer != EOF);
}
}
else return;
}
}
//以姓名升序排序;若姓名一样,则按手机号码升序排序
static int cmp(struct People a, struct People b)
{
if (strcmp(a.name, b.name) > 0)
{
return 1;
}
if (strcmp(a.name, b.name) < 0)
{
return 0;
}
if (strcmp(a.phone, b.phone) >= 0)
{
return 1;
}
return 0;
}
void sort_contacts(struct Peoples *contacts)
{
qsort(contacts->contact, contacts->i, sizeof(contacts->contact[0]), cmp);
}
int main()
{
struct Peoples *contacts = (struct Peoples *)malloc(sizeof(struct Peoples) + sizeof(struct People));
contacts->i = 0;
add_contact(contacts);
sort_contacts(contacts);
free(contacts);
return 0;
}