链接列表头地址更改C.

我创建了我的结构的链接列表,但由于某种原因,每次我添加另一个链接它改变头地址,但我希望y头地址是第一个条目。 这是我的代码:

struct checkPoints *tgh = NULL; struct checkPoints **linkedlist = &tgh; struct checkPoints *cp = malloc(sizeof (struct checkPoints)); chPo = fopen(fileName, mode); if (chPo == NULL) { printf("Can't find the files."); exit(1); } else { for (i = 0; i dropOut, &cp->currentPoint, &cp->competitor, &cp->hour, &cp->minute); cp->next = NULL; if (*linkedlist == NULL) { printf("ONCE"); *linkedlist = cp; } else { struct checkPoints *new = *linkedlist; while (new->next != NULL) { new = new->next; } new->next = cp; } } } 

每个fscanf发生它改变头地址到下一个,任何想法?

此行fscanf(chPo, "%c %d %d %d:%d\n", &cp->dropOut, &cp->currentPoint, &cp->competitor, &cp->hour, &cp->minute);地址更改: fscanf(chPo, "%c %d %d %d:%d\n", &cp->dropOut, &cp->currentPoint, &cp->competitor, &cp->hour, &cp->minute);

结构是这样的:

 struct checkPoints{ char dropOut; int currentPoint; int competitor; int hour; int minute; struct checkPoints *next; }; 

这里的问题是您没有分配新节点,您只有一个节点可以反复更改。 您需要在循环内分配节点。

我没有看到任何malloc / calloc来创建新节点,这些节点将被添加到列表中。

您需要创建新节点,这些节点将添加到列表中。 正确的位置就在此之前

  cp->next = NULL; 

线

在您的情况下,您正在分配单个节点并在同一地址中写入数据。

您需要为循环内的新节点分配内存。

必须在循环的开头添加以下行,

struct checkPoints * cp = malloc(sizeof(struct checkPoints));

您需要为读取的每一行分配一个新的struct checkPoints 。 它会给你一个循环:

 struct checkPoints *linkedlist = NULL; /* … */ for (i = 0; i < lines; i++) { struct checkPoints *cp = malloc(sizeof(struct checkPoints)); fscanf(chPo, "%c %d %d %d:%d\n", &cp->dropOut, &cp->currentPoint, &cp->competitor, &cp->hour, &cp->minute); cp->next = NULL; if (linkedlist == NULL) { linkedlist = cp; } else { struct checkPoints *new = linkedlist; while (new->next != NULL) { new = new->next; } new->next = cp; } } 

请注意,这种处理方式非常低效,因为它需要为每一行再次扫描整个列表。 您应该保留指向列表尾部的指针,以便可以在没有while循环的情况下追加。 一个聪明的选择是将每一行添加到列表的前面,一旦你读完整个文件,就会反转整个列表。

 struct checkPoints *cp; for (i = 0; i < lines; i++) { cp = malloc(sizeof(struct checkPoints)); fscanf(chPo, "%c %d %d %d:%d\n", &cp->dropOut, &cp->currentPoint, &cp->competitor, &cp->hour, &cp->minute); cp->next = linkedlist; linkedlist = cp; } cp = linkedlist; linkedlist = NULL; struct checkPoints *next = cp; while (cp) { next = cp->next; cp->next = linkedlist; cp = next; }