首页 > 解决方案 > 读取 .csv 文件并使用 C 将数据分配到多维数组中的内存问题

问题描述

我应该先说我对 C 的经验绝对为零。但是,我需要用它来为我正在做的 CFD 模拟编写 UDF。

我的问题是我必须读取一个 .csv 文件并将这些值导入二维数组,这样我就可以在模拟期间访问这些值。我设法让代码正确读取和打印 .csv 文件中的数据。但是,当我尝试转换然后将该数据添加到数组时,一切都会中断。

我正在使用 strtod() 来转换读取的数据。似乎这种转换有效并给出了正确的值。但是,当我添加代码以将其分配给数组时,代码无法读取整个 .csv 文件,大约在中途停止。我认为这与内存问题有关(虽然不确定),因此我尝试使用指针和 free() 函数。虽然这似乎根本没有帮助。事实上,它只是抛出错误“试图释放非堆对象”。

谁能告诉我哪里出错了?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char str[128];
    int result;
    int width = 2;
    int csvlength = 224;
    double d;
    double data[csvlength][width];
    int counter=0;  // counter to move between fields

    FILE* f = fopen("vindisc.csv", "r");  // instantiate file object as pointer to allow for dynamic size.

    do {
        result = fscanf(f, "%127[^,\n]", str);  // get the result

        /* If it is end of line, skip */
        if(result == 0)
        {
            result = fscanf(f, "%*c");
        }

        /* otherwise, read in the data */
        else
        {
            if (counter%2 == 0) {
                printf("Field_1: %s\n", str);  
                d = strtod(str, NULL);
                //printf("Double test 1: %g\n", d);
                data[counter][0] = d;
            }
            else {
                printf("Field_2: %s\n", str);
                d = strtod(str, NULL);
                //printf("Double test 2: %g\n", d);
                data[counter][1] = d; 
            }
            
            counter++;  // update the counter
        }
        //free(&str);
    } while(result != EOF);  // close the file after the read.

    for(int i = 0; i < csvlength; i++) {
        printf("%g", data[i][0]);
        printf("\n");  
        printf("%g", data[i][1]);
        printf("\n");   
    }
    return 0;
}

添加了 csv 文件的摘录以显示结构。

标签: arraysccsvmultidimensional-array

解决方案


推荐阅读