【发布时间】:2018-10-09 07:38:50
【问题描述】:
FILE *fd;
char **lines = NULL;
int err = fopen_s(&fd, filename, "r");
if (err != 0) {
printf("Nao foi possivel abrir o ficheiro %s ...\n", filename);
return;
}
char nextline[1024];
int counter = 0;
while (fgets(nextline, sizeof(nextline), fd)) {
if (strlen(nextline) < 1) {
continue;
}
lines = (char**)realloc(lines, (counter+1) * sizeof(*lines));
lines[counter] = nextline;
counter++;
}
fclose(fd);
*numElements = counter;
//IN HERE IT SHOWS ME THE SAME FOR ALL THE PLAYERS FROM 300 DIFFERENT PLAYERS WHY IS THAT???
printf_s("\n\n%s\n", lines[299]);
printf_s("%s\n", lines[298]);
我无法解决问题。
首先 realloc 正在删除旧缓冲区,现在它实际上是将相同的数据复制到所有 300 个索引。
有人可以帮帮我吗?
【问题讨论】:
-
当然它们都是一样的,它们都指向同一个缓冲区。如果不想被下一行覆盖,则需要将数据从缓冲区中复制出来。 Realloc 做的正是它应该做的,但是这一行依次为每个索引分配了相同的值。
lines[counter] = nextline;