#include <stdio.h>
#include <stdlib.h>
int main() {
int row = 0, colu = 3, j, i;
FILE *fp;
fp = fopen("file.txt", "r");
fscanf(fp, "%d", &row);
int *arr = (int *)malloc(row * colu * sizeof(int));
for (i = 0; i < row; i ) {
for (j = 0; j < col; j ) {
*(arr i * col j) = i j;
printf("%d ", *(arr i * col j));
}
printf("\n");
}
}
So I was able to make a 2D array using malloc
but now I want to get information from a file and store it into my 2D array.
The File:
4
34.1 54.2 54
23.4 19.5 53.2
43.2 54.2 54.2
53.2 62.4 27.5
and so on......
In the first line is the number of rows I will use. I already figured out how to do that. But now I want to store the numbers below "4" into a 2D array. How could I do this. Sorry if I did not explain this too well, I'm new to coding.
CodePudding user response:
... to store the numbers below "4" into a 2D array.
Add a fscanf()
to store into the 1D array pointed to by arr
.
Consider adding error checking too.
if (fscanf(fp, "%d ", arr i * col j) != 1) {
fprintf(stderr, "Failed to read.\n");
exit(-1);
}
printf("%d ", *(arr i * col j));
I was able to make a 2D array using malloc
Code did not make allocate a 2D array. Just a 1D array.
More worked needed for a 2D array.
CodePudding user response:
Function fscanf
takes an address of the object to which it writes scanned data. It returns a number of successfully scanned elements whiat is going to be 1
in your case. That it why typical usage of scanf
-like function is following.
int data;
if (scanf("%d", &data) != 1)
... error handling ...
... use data ...
Actually, you don't use 2D array in your code but rather emulate it using 1D array. To create a true dynamic 2D array you should use a pointer to a Variable-Length Array (VLA). Below you can find a updated version enhanced with error handling which is strongly recommended when working with files.
#include <stdio.h>
#include <stdlib.h>
int main() {
int rows = 0, cols = 3, j, i;
FILE *fp;
fp = fopen("file.txt", "r");
if (!fp) {
fprintf(stderr, "failed to open file.txt");
exit(-1);
}
if (fscanf(fp, "%d", &rows) != 1) {
fprintf(stderr, "failed to read number of rows");
exit(-1);
}
// allocate memory for `row` elements of type `*arr` which is `int[cols]`
int (*arr)[cols] = calloc(rows, sizeof *arr);
if (!arr) {
fprintf(stderr, "out of memory");
exit(-1);
}
for (i = 0; i < rows; i ) {
for (j = 0; j < cols; j ) {
if (fscanf(fp, "%d", &arr[i][j]) != 1) {
fprintf(stderr, "failed to parse entry at [%d,%d]", i, j);
exit(-1);
}
}}
for (i = 0; i < rows; i ) {
for (j = 0; j < cols; j )
printf("%d ", arr[i][j]);
puts(""); // newline
}
free(arr);
}