c - 在 C 中使用动态分配将文件读入多维数组

标签 c multidimensional-array dynamic-memory-allocation

在 C 语言中,如何将具有如下结构的文件中的数据读取到多维整数数组中?

文件:

3 4 30 29
23 43 4 43

我需要使用动态分配将其放入“int** 矩阵”变量中。

更新:

我想要一个示例代码,我可以查看它并研究下面列出的功能之间的关系:

  • 多维数组及其与指针到指针的关系;
  • 内存的动态分配及其使用的一些解释;
  • 如何处理来 self 们不知道其大小的外部源的数据,如何在 C 程序中将行/列分隔到我们的数组中。

分享代码:

int** BuildMatrixFromFile(char* infile, int rows, int cols){

    FILE *fpdata;   //  deal with the external file
    int** arreturn; //  hold the dynamic array
    int i,j;        //  walk thru the array 

    printf("file name: %s\n\n", infile);

    fpdata = fopen(infile, "r");    //  open file for reading data

    arreturn = malloc(rows * sizeof(int *));
    if (arreturn == NULL)
    {
        puts("\nFailure trying to allocate room for row pointers.\n");
        exit(0);
    }

    for (i = 0; i < rows; i++)
    {

        arreturn[i] = malloc(cols * sizeof(int));
        if (arreturn[i] == NULL)
        {
            printf("\nFailure to allocate for row[%d]\n",i);
            exit(0);
        }

        for(j=0;j<cols;++j)
            fscanf(fpdata, "%d", &arreturn[i][j]);

    }

    fclose(fpdata); // closing file buffer

    return arreturn;    
}

谢谢。

最佳答案

没有人会为您编写代码。但这里是您可能需要实现此目的的标准库函数列表:

  • fopen()
  • fscanf()
  • fclose()
  • malloc()
  • free()

关于c - 在 C 中使用动态分配将文件读入多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4798618/

相关文章:

从 Matlab 调用 Fortran 中的 C 兼容 DLL

c - C 中作为函数参数的指针为 NULL

php - 复杂且令人困惑的 PHP 数组计算

c - 如何为JNI对象数组动态分配内存

c++ - 函数是否在退出作用域时清除动态内存?

c - 将递归 C 结构移植到 Fortran

c - ls命令如何找到硬链接(hard link)数?

c++ - 如何在二维数组中写入这个模式?

c++ - new int[M][N] 的类型是什么?

c++ - 在 C++ 中为我自己的基于指针的数组分配内存的正确方法