arrays - 读取 .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 文件的摘录以显示结构。
解决方案
推荐阅读
- php - “此页面无法正常工作 xxxxx.com 目前无法处理此请求。HTTP 错误 500”
- javascript - 通过nodejs连接ssh
- android - Android Glide 错误:找不到符号方法 crossFade()
- c - 如何创建二维数组?
- amazon-web-services - 如何每天以不同的时间表触发 aws lambda
- php - php utf8 / unicode 编码
- javascript - 如何将图像名称从 Firebase 存储复制到 Firebase 数据库?Javascript 和 Java
- android - 将数据库信息获取到片段上的 ListView
- r - 在 R 中的 For 循环中嵌套 if 循环以比较条件
- mongodb - 如何在mongodb中创建索引以同时支持多个查询?