-
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
3492
4952
3934
3922
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
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
for(i=0;;i++){
if ((b=fscanf(fip,"%d",&temp[i]) == EOF) break;
if(i>=a){
a=a*2;
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.
Code:
temp=malloc(a*sizeof(int *));
Also, try using fgets() to read from file. It detect EOF better.
Thanks,