Search code examples
cmultidimensional-arraydynamic-memory-allocation

Read a file into a multidimensional array with dynamic allocation in C


How can I read the data from a file with structure like the one below into a multidimensional array of integers in C?

file:

3 4 30 29
23 43 4 43

I need put this inside of an "int** matrix" variable using dynamic allocation.

UPDATED:

I want an example code which I can go over and study the relation between the functionalities listed below:

  • multidimensional arrays and their relation with pointer-to-pointer;
  • dynamic allocation of memory and some explanation about it's use;
  • how to deal with data coming from an external source that we don't know the size of, how separate the rows/cols into our array inside of the C program.

SHARING CODE:

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;    
}

Thank you.


Solution

  • The description starting on page 20 of Numerical Recipes in C will show you one way to allocate the memory. Treat the 2d array as an array of pointers to the rows of your matrix.

    Parsing the lines from the file is accomplished with fopen() and maybe fscanf() to pull out the numbers.