[英]C read a number of lines with fgets
我正在嘗試將文件讀入二維數組。
第一行包含數組的大小(例如4、3),然后我需要創建4x3和3x4數組並讀取值。
我遇到了細分錯誤。 是因為使用sscanf之后需要倒帶嗎?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LINE_LEN 100
int main(int argc, char ** argv)
{
int ** arr1;
int ** arr2;
int i,col,row;
FILE * dfile;
char line[LINE_LEN];
char * token;
int num1,num2;
const char delim[2] = " ";
if ((dfile = fopen(argv[1], "r")) == NULL) {
fprintf(stderr, "Error opening input file.\n");
exit(EXIT_FAILURE);
}
fscanf(dfile, "%d %d\n", &num1, &num2);
arr1 = malloc(num1 * sizeof(int*));
for (i = 0; i < num1; i++) {
arr1[i] = malloc(num2* sizeof(int));
}
arr2 = malloc(num2 * sizeof(int*));
for (i = 0; i < num2; i++)
{
arr2[i] = malloc(num1 * sizeof(int));
}
col = 0;
for(i=0; i<num1; i++)
{
row = 0;
fgets(line, LINE_LEN, dfile);
token = strtok(line, delim);
while (token != NULL)
{
token = strtok(NULL, delim);
arr1[col][row] = atoi(token);
row++;
}
col++;
}
col=0;
for(i=0; i<num2; i++)
{
row=0;
fgets(line,LINE_LEN,dfile);
token = strtok(line,delim);
while(token != NULL)
{
token = strtok(NULL,delim);
arr2[col][row] = atoi(token);
row++;
}
col++;
}
}
文件示例
4 3
0 0 1 2
1 1 0 2
2 1 2 0
3 1 0 2
0 0 1 2 3
2 2 3 1 0
1 2 1 3 0
NULL
傳遞給atoi
函數,它會導致細分失敗。 在將token
傳遞給atoi
之前,檢查token
是否為NULL
。 num1
和num2
行之后的每行上都有一個額外的數字,這會導致越界訪問。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.