gpt4 book ai didi

c - 为什么它会取代初始值?

转载 作者:行者123 更新时间:2023-11-30 16:53:30 26 4
gpt4 key购买 nike

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

一个

b

c

代码将在 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;
};

最佳答案

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

关于c - 为什么它会取代初始值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40836967/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com