要求:
定义一个结构体,存储图书的信息,包括名字、价格和数量
使用结构体数组,数组容量未知 ,存储5本书的信息在数组中
写四个函数
1. 统计有效图书数量
2. 将所有有效图书信息打印出来
3. 在某个位置插入一本书的信息
4. 在某个位置删除一本书的信息
考虑:数组在内存中是连续的,当插入信息时,插入位置后的图书信息对应下标都要 + 1;当删除信息时,删除位置后的图书信息对应下标都要 - 1
代码:
#include<stdio.h>
#include<stdlib.h>
struct book
{
char name[20] ;
int number;
float pc;
};
int size(const struct book* stu)//统计图书数量
{
int n = 0;
while (stu->number != 0)
{
n++;
stu++;
}
return n;
}
void sum(const struct book *stu,int n)//输出图书信息
{
for (int i = 0; i < n; i++)
{
printf("第%d本书的名字,数量和价格:%s,%d,%g\n", i + 1, stu[i].name, stu[i].number, stu[i].pc);
}
}
void insert(struct book* stu, struct book* stu_info, int location,int* n)//插入图书
{
struct book* p = stu;//定义一个变量存放数组的首地址
p += location;//直接定位到需要插入的位置
struct book* p_i= (struct book*)malloc(sizeof(struct book));//定义一个结点来存放需要插入的图书信息
/*memset(stu_info, 0, sizeof(struct book));*///error 不能将p_i初始化
*n += 1;//长度加一
while (p < stu + *n)
{
*p_i = *p; //先保留现在位置的数据
*p = *stu_info;//将现在位置的数据替换成要插入的信息
*stu_info = *p_i;//把现在的信息作为下一个要插入的信息
p++;
}
free(p_i);
p_i = NULL;
}
void delete(struct book* stu, int location, int *n)//删除图书
{
struct book* stu_delete = stu;
stu_delete += location;
*n -= 1;
while (stu_delete < stu + *n)
{
*stu_delete = *(stu_delete + 1);//把下一个数据给当前
stu_delete++;
}
memset(stu+*n,0,sizeof(struct book));//清空多余项
}
int main()
{
struct book* stu = (struct book*)malloc(sizeof(struct book) * 10);//动态分配内存
memset(stu, 0, sizeof(struct book) * 10);//初始化
//struct book stu[10] = {0};
int i = 0;
do
{
printf("输入第%d本书的名字,数量和价格:", i+ 1);
scanf("%s%d%f", &stu[i].name, &stu[i].number, &stu[i].pc);
i++;
} while (i < 5);
//int i = 5;
//for (int x =0 ;x<i;x++)//输入信息
//{
// printf("输入第%d本书的名字,数量和价格:",x+1);
// scanf("%s%d%f",&stu[x].name, &stu[x].number, &stu[x].pc);
//}
printf("\n");
int n = size(stu);
printf("有效书籍数量为%d\n", n);
printf("\n");
sum(stu, n);//输出信息
printf("\n");
struct book* stu_info = (struct book*)malloc(sizeof(struct book));//定义插入的图书信息
memset(stu_info, 0, sizeof(struct book));
printf("请输入要插入图书的信息:");
scanf("%s%d%f", &stu_info->name, &stu_info->number, &stu_info->pc);
int location = 0;
printf("请输入要插入图书的位置:");
scanf("%d", &location);
printf("\n");
insert(stu,stu_info, location, &n);
sum(stu, n);//输出信息
printf("请输入要删除图书的位置:");
scanf("%d", &location);
printf("\n");
delete(stu, location, &n);
sum(stu, n);//输出信息
free(stu);
free(stu_info);
stu = NULL;
stu_info = NULL;
return 0;
}