【发布时间】:2022-01-17 14:37:42
【问题描述】:
我需要解析 csv 文件。我创建字符串数组并为此分配内存 第一个循环while(fgets(line,100,fp)是成功的,但是当它进入第二个时值被line的数据覆盖
while (fgets(line, 100, fp))
{
num_of_string++;
code = (char **)realloc(code, sizeof(char *) * (num_of_string));
occupation = (char **)realloc(occupation, sizeof(char *) * (num_of_string));
num_of_ppl = (char **)realloc(num_of_ppl, sizeof(char *) * (num_of_string));
char * column = strtok(line, ",");
code[num_of_string-1] = malloc(sizeof(char) * (strlen(column)+1));
code[num_of_string-1] = column;
counter++;
while (column)
{
if (counter == 1)
{
column = strtok(NULL, "\"");
occupation[num_of_string-1] = malloc(sizeof(char) * (strlen(column)+1));
occupation[num_of_string-1] = column;
counter++;
column = strtok(NULL, ",");
} else if (counter == 2) {
num_of_ppl[num_of_string-1] = malloc(sizeof(char) * (strlen(column)+1));
num_of_ppl[num_of_string-1] = column;
counter++;
column = strtok(NULL, ",");
} else {
column = strtok(NULL, ",");
counter++;
}
}
counter = 0;
}
【问题讨论】:
标签: c memory allocation