【问题标题】:C read a number of lines with fgetsC 用 fgets 读取多行
【发布时间】:2015-10-18 13:29:28
【问题描述】:

我正在尝试将文件读入二维数组。

第一行包含数组的大小(例如 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

【问题讨论】:

  • fscanf() 可能会失败,就像许多其他返回值的函数一样,您不必费心检查错误。也就是说,我猜你是在某个地方的数组边缘运行,添加输出语句,为你提供你正在编写的信息,或者只是在调试器中运行时检查状态。
  • 您应该使用所有警告和调试信息 (gcc -Wall -Wextra -g) 进行编译并使用调试器 (gdb)

标签: c arrays fgets scanf


【解决方案1】:
  • NULL 被传递给 atoi 函数,它会导致分段错误。 在将token 传递给atoi 之前检查token 是否不是NULL
  • 文件示例不好,因为num1num2之后的每一行都有一个额外的数字,导致越界访问。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多