为什么这会取代初始值?

时间:2016-11-28 03:59:06

标签: c

当我尝试解析文本文件然后仅打印单个链接列表中的内容时,每个值都由于某种原因被第二个最后一个值覆盖。例如,如果列表是

B'/ P>

C

d

代码将在while循环中打印那些正确的行,但是当我尝试在代码末尾打印头字符串时,代码将仅为头部和头部下一个值打印d。

    char buf[1024];
    printf("Enter the file name: ");
    fgets(buf, 1024, stdin);

    char *file_name = strtok(buf, "\n");
    FILE *fp;
    fp = fopen(file_name2,  "r");


    char *throwaway = fgets(buf, 1024, fp);

    struct bit_t *tail;
    struct bit_t *head;
    head = create_node(throwaway);
    printf("%s\n", head->pos1);
    int count;
    count = 0;
    //issue is that it is just overwriting the old results
    while( (fgets(buf, 1024, fp)) != NULL ) {

            printf("String : %s\n", buf);
            tail = insert_tail(head, create_node(buf));

            printf("%s\n", tail->pos1);
    }
    printf("Results : \n");
    printf("%s\n", head->pos1);
    printf("%s\n", head->next->pos1);

struct bit_t *create_node(char *pos1)

{
        struct bit_t *r;
        struct bit_t *current;

    r = malloc(sizeof(struct bit_t));
    if(!r) {
            exit(1);
    }
    r->next = NULL;
    r->pos1 = pos1;
    current = r;

    return current;

}

struct bit_t *insert_head(struct bit_t *head, struct bit_t *node)
{
        node->next = head;
        head = node;
        return node;
}
struct  bit_t *insert_tail(struct bit_t *head, struct bit_t *node)
{
        struct bit_t *current;
        current = head;
        while(current->next !=  NULL) {
                current = current->next;
        }
        current->next = node;

        return node;;
}

开始使用的结构是

struct bit_t {
    char *pos1;

    struct bit_t *next;
};

1 个答案:

答案 0 :(得分:0)

列表中的每个元素都指向buf,但循环中的每次迭代都会覆盖buf的内容。要解决此问题,每个元素都需要为buf的内容分配存储空间,然后复制buf的值。