Open, Read and Print a 2D Array! (What's wrong with my code?)

0

First I reserve some memory using malloc (the file has a [1024][1024] array), after that I open the file using fopen. Then I'm trying to read the file into the reserved memory space. To see if I'm reading it correctly I'm try printing the array but what I get after compiling the code is: "Process returned -1073741819 (0xC0000005) execution time : 1.779 s" Press any key to continue.

Any suggestions?

{

int **A = malloc(sizeof(double[1024][1024]));

FILE *matrizA = fopen("A_1024.dat", "rb");

for(int z = 0; z < 1048576; z++) {
    fread(&A, sizeof(double),1,matrizA);
}

fclose(matrizA);

for (int i = 0; i < 1024; i++) {
    for (int j = 0; j < 1024; j++) {
        printf( "%f ", A[i][j]);
    }
}

free(A);

}
c
multidimensional-array
fopen
fread
reinterpret-cast
asked on Stack Overflow Oct 2, 2019 by Pablo Correa Chandía • edited Oct 2, 2019 by Vlad from Moscow

1 Answer

1

This declaration is wrong because the type of the pointer A is invalid.

int **A = malloc(sizeof(double[1024][1024]));

You have to write

double ( *A )[1024] = malloc(sizeof(double[1024][1024]));

This loop

for(int z = 0; z < 1048576; z++) {
    fread(&A, sizeof(double),1,matrizA);
}

is also wrong. You could write

for( size_t i = 0; i < 1048576; i++) {
    fread( ( double * )A + i, sizeof(double),1,matrizA);
}

I assume that the file contains exactly 1048576 doubles. Otherwise you have to check the return value of the call of fread.

answered on Stack Overflow Oct 2, 2019 by Vlad from Moscow • edited Oct 2, 2019 by Vlad from Moscow

User contributions licensed under CC BY-SA 3.0