在该方法的最后,我所有的测试 printfs 都打印出相同的结果。文件的最后一行。但是 while 循环中的当前 printf 工作正常。出于某种原因,我的节点具有相同的结果。我该如何解决? 这是我的结构单元:
struct unit
{
struct unit * next;
char *name;
};
这是我的链表函数,一条一条地向链表添加行:
void readFile(char fileName[], struct unit * units)
{
FILE * fp;
char *line = NULL;
int length = 1000;
fp = fopen(fileName, "r");
int counter = 0;
int strLength = 0;
struct unit * current;
units = (struct units*)malloc(sizeof(struct unit));
current = units;
while ( getline(&line, &length, fp) != -1)
{
strLength = strlen(&line);
current->name = (char*)malloc(sizeof(char)* strLength);
current->next = (struct units*)malloc (sizeof(struct unit));
strcpy(¤t->name, &line);
printf("\nCurrent: %s",current->name);
current = current->next;
counter++;
}
printf("\nTest %s", units->name);
printf("\nTest %s", units->next->name);
printf("\nTest %s", units->next->next->name);
printf("\nTest %s", units->next->next->next->name);
}
最佳答案
为什么要将 &line
传递给 strlen
和 strcpy
?如果我没记错的话,你应该将 line
和 current->name
传入这些函数。 (虽然我不知道 getline
;也许这样没问题。)
关于c - 链表给出相同的结果 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21767821/