首页 > 解决方案 > 链表问题中字符串的动态分配

问题描述

我创建了 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

标签: clinked-listdynamic-memory-allocation

解决方案


如果char aux_id[6];长度为 6,则 "332312" 太大,您需要为终止符号 '\0' 留出空间来处理字符串函数。


推荐阅读