简体   繁体   English

从文件读取到 C 中的二维数组,没有固定大小

[英]Reading from file into 2d Array in C without constant size

I have a text file that have content like this我有一个包含这样内容的文本文件

5 6
01111
11110
01000
01111
11010
11111

And i want to made a function read from this file and create 2d array out of the content.我想从这个文件中读取一个 function 并从内容中创建二维数组。

Two Numbers from the first line is the size of array and the size of sub array.第一行的两个数字是数组的大小和子数组的大小。

The result of the function should be array like this function 的结果应该是这样的数组

{{0,1,1,1,1}, {1,1,1,1,0},{0,1,0,0,0},{0,1,1,1,1},{1,1,0,1,0},{1,1,1,1,1}}

So how would i be able to do that?那我怎么能做到呢?

Right now i try to made a function like this but it error现在我尝试像这样制作 function 但它错误

int** createArray(FILE *fp)
{
    int xdim;
    int ydim;
    fscanf(fp, "%d %d", &xdim, &ydim);

    int** arr = malloc(ydim * sizeof(*arr));;
    for (int y = 0; y < ydim; y++)
    {
        arr[y] = malloc(xdim * sizeof(**arr));
        fscanf(fp, "%d %d %d %d", arr[y]);
    }
    return arr;
}

Just loop xdim times over arr[y] then and read numbers with fscanf .只需在arr[y]上循环xdim次,然后使用fscanf读取数字。 Note that a space " " in fscanf format specifier ignores all whitespaces - tabs, spaces and newlines - so it can just read it all.请注意, fscanf格式说明符中的空格" "会忽略所有空格——制表符、空格和换行符——因此它可以全部读取。

int** arr = malloc(ydim * sizeof(*arr));;
if (arr == NULL) {
     abort();
}

for (int y = 0; y < ydim; y++) {

    arr[y] = malloc(xdim * sizeof(*arr[y]));
    if (arr[y] == NULL) {
        abort();
    }

    for (int i = 0; i < xdim; ++i) {
        char c;
        if (fscanf(fp, " %c", &c) != 1) {
            abort(); // handle error
        }
        arr[i][j] = c - '0';
    }
}

Tested on godbolt .在godbolt上测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM