[英]Program that reserves a seats in a few buses with various number of seats using dynamic allocation (malloc or calloc)
I have to make a program that reserves a seats in a few buses (every bus have a different number of seats).我必须制作一个程序,在几辆公共汽车上预留座位(每辆公共汽车都有不同数量的座位)。 I have to use malloc or calloc.我必须使用 malloc 或 calloc。 It has to store info about name and surname and assign it to a seat.它必须存储有关姓名和姓氏的信息并将其分配给座位。 When seat are already occupied it has to give an info "seat already taken".当座位已经被占用时,它必须提供“座位已被占用”的信息。 It also has to error handling.它还必须进行错误处理。 I am begginer and I don't know what to do.我是初学者,我不知道该怎么做。
#include <stdlib.h>
#define max_name 32
int main()
{
int n_buses,n_seats,zm;
char*** tab;
printf("Number of buses:");
scanf("%d", &n_buses);
tab=calloc(n_buses,sizeof(char**));
for(int i=0;i<n_buses;i++)
{
printf("Number of seats in bus %d: ", i+1);
scanf("%d", &zm);
tab[i]=calloc(zm,sizeof(char*));
}
for(int i=0;i<n_buses;i++)
{
for(j=0;j<max_name;j++)
{
tab[i][j]=calloc(max_name,sizeof(char));
}
}
for(i=0;i<n_buses;i++)
{
if(tab[i]) free(tab[i]);
}
if(tab) free(tab);
return 0;
}```
Take a step back away from this pointer-to-pointer-to-pointer and consider what would make an easy to use data type instead.从这个指针到指针到指针退后一步,考虑一下什么可以使数据类型易于使用。 You have buses, seats and passengers, so it makes sense to come a couple of structs to handle the abstraction for that:你有公共汽车、座位和乘客,所以有几个结构来处理抽象是有意义的:
typedef struct
{
char* forename;
char* lastname;
} passenger_t;
typedef struct
{
int total_seats;
passenger_t seat[];
} bus_t;
The last struct uses a trick called flexible array member to allow a variable-sized array at the end of a struct.最后一个结构使用一种称为灵活数组成员的技巧来允许在结构的末尾使用可变大小的数组。 You'd allocate memory for it as:您将为其分配 memory 为:
int seats = 100;
bus_t* my_bus = calloc( seats, sizeof(*my_bus) + sizeof(passenger_t[seats]) );
if(my_bus == NULL) { /* handle errors */ }
my_bus->total_seats = seats;
Now every seat is represented by an allocated passenger_t
item in the seat
array, each item with two pointers set to null by calloc
(malloc wouldn't set them to null).现在每个座位都由seat
数组中分配的passenger_t
_t 项目表示,每个项目都有两个指针,由calloc
设置为 null(malloc 不会将它们设置为 null)。 You can use this to keep track of if a seat is free or taken.您可以使用它来跟踪座位是空闲还是占用。
Add a passenger:添加乘客:
if(n >= my_bus->total_seats) // check that input is valid
{
/* error handling */
}
if(my_bus->seat[n].forename != NULL)
{
my_bus->seat[n].forename = ... /* allocate room for forename then strcpy to it*/
my_bus->seat[n].lastname = ... /* allocate room for lastname then strcpy to it*/
}
Note how we only have one array here and one level of indirection, so this code turns out much easier to read and maintain.注意我们这里只有一个数组和一级间接,所以这段代码更容易阅读和维护。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.