You are allocating a two-dimensional array but are indexing it as if it was a one-dimensional array simulating a two-dimensional array. You need to make up your mind.
Here's an example using a 1-d array to simulate a 2-d array.
Code:
#include <stdio.h>
#include <stdlib.h>
#define INPUT "ulaz4.txt"
int main() {
FILE *in = fopen(INPUT, "r");
int n = 0;
fscanf(in, "%d", &n);
int *matrix = malloc(n * n * sizeof *matrix);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
fscanf(in, "%d", &matrix[i * n + j]);
printf("%3d ", matrix[i * n + j]);
}
printf("\n");
}
fclose(in);
printf("\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
printf("%3d ", matrix[i * n + j]);
printf("\n");
}
free(matrix);
return 0;
}
Here's an example allocating a 2-d array with non-contiguous data (i.e., each row is separately allocated).
Code:
#include <stdio.h>
#include <stdlib.h>
#define INPUT "ulaz4.txt"
int main() {
FILE *in = fopen(INPUT, "r");
int n = 0;
fscanf(in, "%d", &n);
int **matrix = malloc(n * sizeof *matrix);
for (int i = 0; i < n; i++) {
matrix[i] = malloc(n * sizeof **matrix);
for (int j = 0; j < n; j++) {
fscanf(in, "%d", &matrix[i][j]);
printf("%3d ", matrix[i][j]);
}
printf("\n");
}
fclose(in);
printf("\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
printf("%3d ", matrix[i][j]);
printf("\n");
}
for (int i = 0; i < n; i++)
free(matrix[i]);
free(matrix);
return 0;
}
Here's an example allocating a 2-d array with contiguous data (i.e., all rows are allocated together so that they are contiguous).
Code:
#include <stdio.h>
#include <stdlib.h>
#define INPUT "ulaz4.txt"
int main() {
FILE *in = fopen(INPUT, "r");
int n = 0;
fscanf(in, "%d", &n);
// allocate space for matrix row pointers
int **matrix = malloc(n * sizeof *matrix);
// allocate space for matrix data
matrix[0] = malloc(n * n * sizeof **matrix);
// set the row pointers
for (int i = 1; i < n; i++)
matrix[i] = matrix[i - 1] + n;
// fill the matrix with data
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
fscanf(in, "%d", &matrix[i][j]);
printf("%3d ", matrix[i][j]);
}
printf("\n");
}
fclose(in);
printf("\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
printf("%3d ", matrix[i][j]);
printf("\n");
}
free(matrix[0]); // free matrix data
free(matrix); // free matrix row pointers
return 0;
}