Read a file into a multidimensional array with dynamic allocation in C -
how can read data file structure 1 below multidimensional array of integers in c?
file:
3 4 30 29 23 43 4 43 i need put inside of "int** matrix" variable using dynamic allocation.
updated:
i want example code can go on , study relation between functionalities listed below:
- multidimensional arrays , relation pointer-to-pointer;
- dynamic allocation of memory , explanation it's use;
- how deal data coming external source don't know size of, how separate rows/cols our array inside of c program.
sharing code:
int** buildmatrixfromfile(char* infile, int rows, int cols){      file *fpdata;   //  deal external file     int** arreturn; //  hold dynamic array     int i,j;        //  walk thru array       printf("file name: %s\n\n", infile);      fpdata = fopen(infile, "r");    //  open file reading data      arreturn = malloc(rows * sizeof(int *));     if (arreturn == null)     {         puts("\nfailure trying allocate room row pointers.\n");         exit(0);     }      (i = 0; < rows; i++)     {          arreturn[i] = malloc(cols * sizeof(int));         if (arreturn[i] == null)         {             printf("\nfailure allocate 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.
the description starting on page 20 of numerical recipes in c show 1 way allocate memory. treat 2d array array of pointers rows of matrix.
parsing lines file accomplished fopen() , maybe fscanf() pull out numbers.
Comments
Post a Comment