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
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;
fip = fopen("temp.txt", "r");
//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
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.
Also, try using fgets() to read from file. It detect EOF better.