|
发表于 2023-5-31 20:59:53
|
显示全部楼层
这份代码出现问题的地方在于 struct X x[s] 是定义在 for 循环块内的局部变量,循环结束后变量 x 的生命周期就结束了,a[i] 就指向了一个已经不存在的结构体数组,这种悬垂指针的错误会导致不可预知的结果,程序会出现崩溃、段错误等问题。在 C 语言中要想动态申请结构体数组需要使用 malloc 函数,并且不要忘记在使用完之后释放内存。建议你可以参考下面的代码实现:
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- struct ApplyRecord {
- char name[11]; // 姓名
- char id[19]; // 身份证号
- int health; // 健康状况(1 表示身体状况良好,0 表示身体状况不好)
- char time[6]; // 提交时间
- };
- int main() {
- int d, p;
- scanf("%d %d", &d, &p);
- struct ApplyRecord **apply_records = (struct ApplyRecord **)malloc(d * sizeof(struct ApplyRecord *));
- for (int i = 0; i < d; i++) {
- int s, q;
- scanf("%d %d", &s, &q);
- apply_records[i] = (struct ApplyRecord *)malloc(s * sizeof(struct ApplyRecord));
- for (int j = 0; j < s; j++) {
- scanf("%s %s %d %s", apply_records[i][j].name, apply_records[i][j].id, &apply_records[i][j].health, apply_records[i][j].time);
- }
- }
- int count = 0; // 已经发放口罩的数量
- for (int i = 0; i < d; i++) {
- for (int j = 0; j < p && count < apply_records[i]; j++) {
- for (int k = 0; k < apply_records[i]; k++) {
- if (strcmp(apply_records[i][k].time, "24:00") > 0) { // 如果时间是第二天的提交记录,则当作第一天的记录处理
- apply_records[i][k].time[0] = '0'; // 将第二天的第一位数字改为 0
- }
- if (apply_records[i][k].health == 1) { // 如果身体状况良好
- printf("%s %s\n", apply_records[i][k].name, apply_records[i][k].id); // 输出该记录的姓名和身份证号
- apply_records[i][k].health = -1; // 将健康状况改为 -1,表示已经处理过
- }
- else if (apply_records[i][k].health == 0 && ++count <= p) { // 如果身体状况不好且未发放总量超过 p
- printf("%s %s\n", apply_records[i][k].name, apply_records[i][k].id); // 输出该记录的姓名和身份证号
- }
- }
- }
- }
- // 输出所有健康状态为 1 的申请记录
- for (int i = 0; i < d; i++) {
- for (int j = 0; j < apply_records[i]; j++) {
- if (apply_records[i][j].health == 1) { // 如果身体状况良好且未处理过
- printf("%s %s\n", apply_records[i][j].name, apply_records[i][j].id); // 输出该记录的姓名和身份证号
- apply_records[i][j].health = -1; // 将健康状况改为 -1,表示已经处理过
- }
- }
- }
- // 释放申请的内存
- for (int i = 0; i < d; i++) {
- free(apply_records[i]);
- }
- free(apply_records);
- return 0;
- }
复制代码 |
|