C语言 将数据文件读入 2D 数组后出现分段错误



当我尝试运行代码将数据文件读取到 2D 数组中时,我遇到分段错误。不确定我是否没有正确传递数组,或者我是否正确地将文件读取到数组中。

#include <stdio.h>
#include <stdlib.h>
void two_D_input(FILE *fp, int **arr, int* r, int* c)
{
        size_t count;
        char *line = malloc(20);
        while(getline(&line, &count, fp) != 1) {
                for(; count > 0; count--, *c++)
                        sscanf(line, "%d", *&arr[*r][*c]);
                *r++;
        }
}
main()
{
        int a, b, i, j;
        int* array[10][10];
        FILE *f;
        f = fopen("test", "r");
        two_D_input(f, &array[0][0], &i , &j);
        for(a =0; a < i; a++){
                for(b=0;b<j; b++){
                        printf("n%d", array[a][b]);
                }
        }
        fclose(f);
}

文件测试现在看起来像这样。

1    0
1    1

花了一点时间来理解你想做什么。如果我理解正确,您想声明一个M x N大小的静态数组,然后two_D_input填充最多 M x N 个元素,返回通过指针填充的实际colrc.

这样做没有错,但您必须强制读取(或初始化)每行相同数量的列,以便读取的列数的值最终不会指向未初始化的值。您还必须防止读取超出数组的限制。

虽然您可以在将每行数据解析为整数值之前使用 getline 读取每一行数据,但它只是一个易于使用的静态声明缓冲区并在 two_D_inputfgets。(它还消除了free getline分配的内存的需要)

将所有部分放在一起,您可以编写类似于以下内容two_D_input函数:

enum { NROW = 10, NCOL = 10, MAXC = 256 };
...
void two_D_input (FILE *fp, int (*arr)[NCOL], int *r, int *c)
{
    char buf[MAXC] = "";          /* temp buffer to hold line */
    int tmp = 0, tmpc = 0;        /* temp int and column val  */
    *r = *c = 0;                  /* initialize row, col ptrs */
    while (fgets (buf, MAXC, fp)) {     /* read line into buf */
        char *p = buf;
        int n = 0;    /* read int into tmp, get offset in buf */
        while (tmpc < NCOL && sscanf (p, " %d%n", &tmp, &n) == 1)
        {          /* while cols < NCOL & value read from buf */
            arr[*r][tmpc++] = tmp;      /* assign array value */
            if (tmpc > *c) *c = tmpc;   /* update colum width */
            p += n;                 /* update p for next read */
        }
        if (*c != tmpc) {
            fprintf (stderr, "error: invalid column count.n");
            exit (EXIT_FAILURE);
        }
        (*r)++, tmpc = 0;         /* increment row, reset col */
        if (*r == NROW)          /* check against max row val */
            break;
    }
}

(不要忘记(*r)++递增指向的值 r*r++递增指针r

将它们放在一起,您可以执行以下操作:

#include <stdio.h>
#include <stdlib.h> /* for exit */
enum { NROW = 10, NCOL = 10, MAXC = 256 };
void two_D_input (FILE *fp, int (*arr)[NCOL], int *r, int *c)
{
    char buf[MAXC] = "";          /* temp buffer to hold line */
    int tmp = 0, tmpc = 0;        /* temp int and column val  */
    *r = *c = 0;                  /* initialize row, col ptrs */
    while (fgets (buf, MAXC, fp)) {     /* read line into buf */
        char *p = buf;
        int n = 0;    /* read int into tmp, get offset in buf */
        while (tmpc < NCOL && sscanf (p, " %d%n", &tmp, &n) == 1)
        {          /* while cols < NCOL & value read from buf */
            arr[*r][tmpc++] = tmp;      /* assign array value */
            if (tmpc > *c) *c = tmpc;   /* update colum width */
            p += n;                 /* update p for next read */
        }
        if (*c != tmpc) {
            fprintf (stderr, "error: invalid column count.n");
            exit (EXIT_FAILURE);
        }
        (*r)++, tmpc = 0;         /* increment row, reset col */
        if (*r == NROW)          /* check against max row val */
            break;
    }
}
int main (int argc, char **argv)
{
    int array[NROW][NCOL] = {{0}};
    int i, j, r = 0, c = 0;
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
    if (!fp) {
        fprintf (stderr, "error: file open failed '%s'.n", argv[1]);
        return 1;
    }
    two_D_input (fp, array, &r, &c);
    printf ("n read (%d x %d) arraynn", r, c);
    if (fp != stdin)
        fclose (fp);
    for (i = 0; i < r; i++) {
        for (j = 0; j < c; j++) printf (" %2d", array[i][j]);
        putchar ('n');
    }
    return 0;
}

示例输入文件

$ cat dat/a2d.txt
1    0
1    1
$ cat ../dat/10by10.txt
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
50 51 52 53 54 55 56 57 58 59
60 61 62 63 64 65 66 67 68 69
70 71 72 73 74 75 76 77 78 79
80 81 82 83 84 85 86 87 88 89
90 91 92 93 94 95 96 97 98 99

示例使用/输出

$ ./bin/a2dfscanf <dat/a2d.txt
 read (2 x 2) array
  1  0
  1  1
$ ./bin/a2dfscanf <../dat/10by10.txt
 read (10 x 10) array
  0  1  2  3  4  5  6  7  8  9
 10 11 12 13 14 15 16 17 18 19
 20 21 22 23 24 25 26 27 28 29
 30 31 32 33 34 35 36 37 38 39
 40 41 42 43 44 45 46 47 48 49
 50 51 52 53 54 55 56 57 58 59
 60 61 62 63 64 65 66 67 68 69
 70 71 72 73 74 75 76 77 78 79
 80 81 82 83 84 85 86 87 88 89
 90 91 92 93 94 95 96 97 98 99

查看一下,如果您有任何问题,请告诉我。

像这样改变:

#include <stdio.h>
#include <stdlib.h>
void two_D_input(FILE *fp, int arr[][10], int *r, int *c){
    size_t count = 0;
    char *line = NULL;
    *r = *c = 0;
    while(getline(&line, &count, fp) != -1) {
        char *readPos = line;
        int readLen = 0, col = 0;
        while(col < 10 && 1==sscanf(readPos, "%d%n", &arr[*r][col], &readLen)){
            readPos += readLen;
            ++col;
        }
        *c = col;//It is necessary all the same number of columns
        ++*r;//or (*r)++;
    }
    free(line);
}
int main(void){
    int a, b, i, j;
    int array[10][10];
    FILE *f;
    f = fopen("test", "r");
    two_D_input(f, array, &i , &j);
    for(a = 0; a < i; a++){
        for(b = 0; b < j; b++){
            printf("%d ", array[a][b]);
        }
        putchar('n');
    }
    fclose(f);
    return 0;
}

相关内容

  • 没有找到相关文章

最新更新