c - 链表问题中字符串的动态分配
问题描述
我创建了 2 个函数,它们从一个文件中读取一些数据并将数据写入另一个文件,但是在该列表中使用链表和动态分配的字符串,但是我有一个找不到的逻辑错误:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct product {
char id[6];
char *name;
int price;
struct product *next;
};
struct product *read(struct product *head, FILE *input) {
struct product *p, *q, *aux;
p = (struct product *)malloc(sizeof(struct product));
char aux_id[6];
char aux_name[20];
int aux_price;
fscanf(input, "%s %s %d", aux_id, aux_name, &aux_price);
strcpy(p->id, aux_id);
p->name = (char *)malloc(strlen(aux_name) * (sizeof(char)));
strcpy(p->name,aux_name);
p->price = aux_price;
p->next = NULL;
head = p;
while (fscanf(input, "%s %s %d", aux_id, aux_name, &aux_price) != EOF) {
q = (struct product *)malloc(sizeof(struct product));
q->name = (char *)malloc(strlen(aux_name) * (sizeof(char)));
q->next = NULL;
strcpy(q->name, aux_name);
strcpy(q->id, aux_id);
q->price = aux_price;
p->next = q;
p = q;
}
return head;
}
void write(struct product *head, FILE *output) {
struct product *p;
p = head;
while (p != NULL) {
fprintf(output, "%s %s %d\n", p->id, p->name, p->price);
p = p->next;
}
}
int main() {
struct product *head, *p, *q;
FILE *input = fopen("input.txt", "r+");
FILE *output = fopen("output.txt", "w+");
head = read(head, input);
write(head, output);
fclose(input);
fclose(output);
}
输入文件如下所示:
333444 Cola 3
332312 Pepsi 4
123451 Mountain 3
输出文件看起来像这样
333444 Cola 3
332312°)q 4
123451à)q 3
解决方案
如果char aux_id[6];
长度为 6,则 "332312" 太大,您需要为终止符号 '\0' 留出空间来处理字符串函数。
推荐阅读
- bash - Bash:从刚刚被捕获的错误中获取消息
- c# - 单元测试服务中如何模拟存储库方法
- azure - 使用 ManagedServiceIdentity 从逻辑应用程序到 Azure 函数时出现 301 永久重定向
- javascript - JavaScript 购物车无法正常运行
- c++ - 无法从派生类对象访问父类函数
- c# - 根据该键的属性确定字典是否包含键?
- java - 运算符 <= 不能应用于“E”、“E”、泛型类
- sql - PostgreSQL:使用单个查询更新表中的多行
- c# - 单个参数字符串被视为多个参数 c# QueryHelpers
- mysql - Django Rest API:查看定义删除查询集