c语言 - 数组被 while 循环覆盖,它们都有相同的数据



我有一个包含电视节目的文本文件。第一列是频道的名称,第二列是频道开始的时间,第三列是标题。我想用while循环来分解我的文本文件,但当我在循环外检查时,数组中的所有数据都会被最后一个覆盖。请有人帮我:(

int i = 0;
FILE *f;
f = fopen("tvmusor.txt", "r");
if (!f)
{
printf("error", f);
getchar();
return -1;
}
char *buf = (char *)malloc(100);
char **chan = (char **)malloc(sizeof(char *) * 300);
char **time = (char **)malloc(sizeof(char *) * 300);
char **prog = (char **)malloc(sizeof(char *) * 300);
for (i = 0; i < 300; i++)
{
chan[i] = (char *)malloc(sizeof(char) * 30);
time[i] = (char *)malloc(sizeof(char) * 30);
prog[i] = (char *)malloc(sizeof(char) * 30);
}
i = 0;
while (!feof(f))
{
memset(buf, 0, 100);
if (fgets(buf, 100, f) == NULL)
continue;
if (strlen(buf) > 0 && strchr(buf, 't') != NULL)
{
chan[i] = strtok(buf, "t");
time[i] = strtok(0, "t");
prog[i] = strtok(0, "n");
printf("%st%st%sn", chan[i], time[i], prog[i]);
}
i++;
}

您正在分配指针,而不是复制内容。

  1. strtok返回指向在buf中找到的令牌位置的指针。

    因此,当您退出循环时,chan[i]time[i]prog[i]指针将指向buf的最新内容。

  2. 此外,当用strok覆盖chan[i]time[i]prog[i]时,也会出现memory泄漏。

因此更改此

chan[i] = strtok(buf, "t");
time[i] = strtok(0, "t");
prog[i] = strtok(0, "n");

strncpy(chan[i], strtok(buf, "t"), 30);
strncpy(time[i], strtok(0, "t"), 30);
strncpy(prog[i], strtok(0, "n"), 30);

警告:来自strncpy如果src的前n个字节中没有空字节,则放置在dest中的字符串不会以null结尾。

最新更新