0

read from a file using dynamic memory

void print2d(){ FILE *fp; int i, j, l=3, c=3; int *ptr; ptr = malloc(l * c * sizeof(ptr)); if (ptr == NULL){ printf("Memory not allocated"); exit(1); } if (!(fp = fopen("arr.txt", "r"))){ printf("Can't open arr.txt"); exit(2); } i=0; j=0; while(!feof(fp)){ fscanf(fp, "%d", (ptr+i*c + j)); i++; if (i==3){ i = 0; j ++; } } for (i = 0; i<l; i++){ for (j = 0; j<c; j++){ printf("%3d", *(ptr + i * c + j)); } } } int main() { print2d(); return 0; } I need to create a function that read a matrix from a file then print the file. Using dynamic memory allocation. This is my attempt and I don't know why is not working.

18th Jun 2020, 7:02 PM
tibi
tibi - avatar
1 ответ
+ 1
Your malloc() call probably allocates more memory than it needs to because it returns the size of the pointer and not the value pointed to. Since you're using a pseudo 2D array, is there a reason for not reading the values into it sequentially? When i hits 3 it is on the 2nd row of your pseudo 2D array, and 6 is on the 3rd, so you can let the loop run until i has read 9 values from the file. So I would change the while loop to: while (fscanf(fp, "%d", &ptr[i]) != EOF) i++; and do an fclose(fp) and free(ptr) at the end. If your file contains more than 9 (or 8 if you count from 0) values you'll need to break out of the fscanf() loop or you will overflow the array buffer, but you can guard against that by limiting the iterations.
18th Jun 2020, 8:15 PM
Gen2oo
Gen2oo - avatar