将CSV元素导入C中的2D数组

我是C的新手。我一直在尝试将csv文件中的整数元素导入C中的数组。当我必须导入行和列较少的CSV文件时,代码工作正常; 例如,我已经尝试使用包含90行和80列的CSV文件。 但是,当CSV具有更多行/列数时,问题就开始了。 具体来说,我正在尝试导入包含238行和320列的CSV文件。 但是程序终止显示“导致该程序停止工作的问题”。 我在代码中提到程序出错了。 请帮帮我,因为我无法知道这个问题背后的原因。

我在其他地方搜索过,但没有找到特定于C的答案。另外,Stackoverflow上有一个类似的问题:(因为,它是针对一维数组,我的方法有所不同,我决定在这里问一个新问题。) CSV到C中的数组

以下是CSV文件的具体链接: https : //drive.google.com/file/d/0BxnaWIgBd3AjbGVrY1FTdFpxemM/edit?usp=sharing

这是我的代码:

#include  #include  #define ARRAYSIZE(x) (sizeof(x)/sizeof(*(x))) int main(void) { const char filename[] = "1.csv"; /* * Open the file. */ FILE *file = fopen(filename, "r"); if ( file ) { int array[320][238]; size_t i, j, k; char buffer[BUFSIZ], *ptr; /* * Read each line from the file. */ for ( i = 0; fgets(buffer, sizeof buffer, file); ++i ) { /* * Parse the comma-separated values from each line into 'array'. */ for ( j = 0, ptr = buffer; j < ARRAYSIZE(*array); ++j, ++ptr ) { array[i][j] = (int)strtol(ptr, &ptr, 10); } /* The problem seems to occur here..after the 237th iteration... "i" begins to advance the iteration to 238 after it has done upto 237 iterations which is making the program hang.....THIS ERROR NEVER OCCURS FOR CSV FILES OF SMALLER DIMENSIONS, SPECIFICALLY SAY 99 rows and 79 columns*/ } fclose(file); /* * Print the data in 'array'. */ for ( j = 0; j < i; ++j ) { printf("array[%lu]: ", (long unsigned)j); for ( k = 0; k < ARRAYSIZE(*array); ++k ) { printf("%4d ", array[j][k]); } putchar('\n'); } } else /* fopen() returned NULL */ { perror(filename); } return 0; } 

此外,我想强调的是,代码对于较小的CSV(如[110] x [90])非常有效,并且迭代在i = 109处完全停止。 但是,对于像这样的更大的数组,“i”并没有停留在237.此外,我事先知道确切的行数和列数。 这不是分配问题,而是循环问题(导致分段错误)。

您正在尝试添加比arrays可容纳的更多行数据。 你将数组声明为int array[320][238]; – 这是320行,238列。 数组基于0,意味着数组的元素运行[0-319][0-237] 。 这就是为什么多达319个工作,但在320上失败。尝试增加数组大小,或者只是声明数组列,然后根据需要动态分配行。

我测试了你的csv文件和以下工作。 我还发现你的数据实际上是238 rows x 320 columns ,如附加答案中所示。 所以是的,你的数组实际上应该是array[238][320] 。 动态分配有其优点:

 #include  #include  #define ARRAY_WIDTH 320 int main (int argc, char *argv[]) { int *array[ARRAY_WIDTH]; int idx = 0; int j = 0; char *buffer = NULL; size_t len = 0; ssize_t read; char *ptr = NULL; FILE *fp; fp = fopen ("test.txt", "r"); //open file , read only if (!fp) { fprintf (stderr, "failed to open file for reading\n"); return 1; } while ((read = getline (&buffer, &len, fp)) != -1) { array[idx] = malloc (sizeof (array)); for (j = 0, ptr = buffer; j < ARRAY_WIDTH; j++, ptr++) array [idx][j] = (int)strtol(ptr, &ptr, 10); idx++; } fclose (fp); int i = 0; for (i=0; i 

这假设你有一个固定的ARRAY_WIDTH。 在你的情况320.注意使用getline而不是fgets ,它是行输入的首选方法。

 int array[320][238];//<<- Rows <-> columns 

改成

 int array[238][320]; 

 char buffer[BUFSIZ] //<<- Buffer size is probably small 

改成

 char buffer[4096]