Thread: Read file in 2D array

  1. #1
    Registered User
    Join Date
    May 2003

    Read file in 2D array

    Hi guys, i got a problem in reading file and don't know how to figure it out. Assum I have this file temp.txt

    3 4

    What i meant to do is create a 2D array has number of row is 3 and column is 4, then read and store these number above (start from line 2) to 2D array.

    I don't know how to do it, so wat i did is make a 1D array read and store these number, then make 2D array and copy third number of 1D array onward to 2D array. But it's not working, and my code keeps running in infinite loop. Is there any other way to do it.

    Here is my sample code
    int a=1, b, i, j, *temp;
    FILE *fip;
    fip = fopen("temp.txt", "r");
    temp=malloc(a*sizeof(int *));
    //Infinite loop happens at here, it doesn't jump to next line of file
                       if ((b=fscanf(fip,"%d",&temp[i]) == EOF) break;
                                          temp=realloc(temp, a*sizeof(int *));

    Thanks in advance

  2. #2
    Registered User
    Join Date
    Apr 2005
    You need to malloc and realloc of the size of integer and not the size of "integer pointer".

    Fortunately, for you both are of same size here. Integer (assuming long) is 4 bytes and the pointer which is nothing but a memory address is also 4 bytes (assuming 32-bit architecture) . However the code is not correct.
    temp=malloc(a*sizeof(int *));
    Also, try using fgets() to read from file. It detect EOF better.


Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Newbie homework help
    By fossage in forum C Programming
    Replies: 3
    Last Post: 04-30-2009, 04:27 PM
  2. Read file into array
    By neobarn in forum C Programming
    Replies: 6
    Last Post: 01-09-2009, 12:41 PM
  3. Read .txt file into 2D array.
    By crazygopedder in forum C Programming
    Replies: 11
    Last Post: 10-21-2008, 08:42 PM
  4. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 05:02 AM
  5. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM