简体   繁体   English

如何在C中使用CSV文件中的字符串(char *)填充2D数组

[英]How to populate a 2D array with Strings (char*) from a CSV file in C

I am working on a project where I am trying to read in a CSV file and check it for all sorts of different parameters. 我正在一个项目中尝试读取CSV文件并检查它的各种不同参数。 C is a new language for me so I am still getting used to it, and my code may not be as streamlined as it could be. C对我来说是一种新语言,因此我仍然习惯它,并且我的代码可能没有像它那样精简。 Anyways, my issue is this: when I read the file to make sure each row has the same number of entries it works fine, but when I try to put the values into a 2D array everything gets messed up. 无论如何,我的问题是这样的:当我读取文件以确保每一行具有相同数量的条目时,它可以正常工作,但是当我尝试将值放入2D数组中时,一切都变得混乱了。 The value at arr[0][0] should be the first value in the CSV file, but when I print out to see what it is, it is always the first value in the last row. arr [0] [0]处的值应该是CSV文件中的第一个值,但是当我打印出要查看的内容时,它始终是最后一行中的第一个值。 I can't for the life of me figure this out, and I have been looking at this code and tinkering with it for hours. 我一生都无法解决这个问题,而且我一直在看这段代码,并花了几个小时来修改它。 Any help would be much appreciated! 任何帮助将非常感激!

int parseFile(int width, int height, char*fileName) {

char*** matrix = malloc(width*height*sizeof(char*));
int counter = 0;
int pointer = 0;
FILE *file = fopen(fileName, "r");
const size_t line_size = 1024;
char* line = (char*) malloc(line_size);

while (fgets(line, line_size, file) != NULL) {
    char** data = malloc(width*sizeof(char*));
    char *delim = ",";
    char *string = strtok(line, delim);
    while (string != NULL) {
       size_t ln = strlen(string) - 1;
        if (string[ln] == '\n') {
            string[ln] = '\0';
        }
        data[counter] = string;

        string = strtok(NULL, delim);
        counter++;
    }
    matrix[pointer] = data;
   counter = 0;
   pointer++;
}
printf("%s", matrix[0][0]);
return 0;

} }

This looks nearly right, but what is happening is strtok is returning a pointer into line. 这看起来几乎是正确的,但是正在发生的事情是strtok将指针返回到行中。 That means it only has copies of the last line. 这意味着它只有最后一行的副本。

Consider creating a new memory slot for each line, or strdup the result from strtok 考虑为每行创建一个新的内存插槽,或者将strtok的结果strdup

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM