fread and fwrite with double pointers in c

1

I'm trying to write an array of structures to a binary file but when I call the function fwrite does not save anything in the file.

Edit: I add the page definition

typedef struct Pagina Pagina;
struct Pagina
{
  char *Instrucción;
  char *register1;
  char *register2;
};


void Escribir_swap(const char *PCB, const char *Archivo, Pagina **Paginas){
FILE *A, *B;
char exeption[5] = " \n\t,";
char LINE[LONG_MAX_LINE];
int TAM = 0;
int i = 0, j = 0;
for(i = 0; i < MARCOS; i++){
    for(j = 0; j < PAGINAS; j++){
        if(Get_I(TAM, PCB, LINE, exeption, A) !=NULL ){
            Paginas[i][j].Instruccion = strdup(Get_I(TAM, PCB, LINE, exeption, A));
            Paginas[i][j].register1 = strdup(Get_R(TAM, PCB, LINE, exeption, A, 1));
            Paginas[i][j].register2 = strdup(Get_R(TAM, PCB, LINE, exeption, A, 2));
            TAM++;
            }
        else{
            break;
        }
      }
    }
printf("I\t R1,R2\n");
for(i = 0; i<MARCOS; i++)
{
    for(j = 0; j<PAGINAS; j++)
    {
            printf("%s\t %s,%s\n", Paginas[i][j].Instruccion, Paginas[i][j].register1, Paginas[i][j].register2);
    }
}
if(B = fopen(Archivo, "wb")==NULL)
{

    printf("Error al abrir archivo %s", Archivo);
    perror(Archivo);
}else
{
    for(i = 0; i<MARCOS; i++)
    {
        for(j=0;j<PAGINAS;j++)
        fwrite(&Paginas[i][j], sizeof(Pagina), 1, B);
    }
}
fflush(B);
fclose(B);
}
    
asked by Juan J. Mart 26.06.2018 в 06:54
source

1 answer

2

If we assume that you are compiling in 32 bits (for example) and we do:

printf("%d\n",sizeof(Pagina));

The number 12 will appear on the screen. In other words, the structure will occupy 12 bytes in memory. How is it possible to occupy only 12 bytes if you can, for example, store the whole quixote in Instruccion ?

The problem here is that the structure uses pointers instead of arrays of fixed size:

struct Pagina
{
  char Instruccion[10];
  char register1[10];
  char register2[10];
};

And for this reason the structure contains only memory addresses ... it does not contain a single valid data. The data is in you know what part of the memory.

I ignore the requirements of the application, so it's up to you to assign the specific size to each array, but the structure should look more like the one I've put 2 paragraphs before. Of course, doing this you can not do assignments:

Paginas[i][j].Instruccion = strdup(Get_I(TAM, PCB, LINE, exeption, A));
Paginas[i][j].register1 = strdup(Get_R(TAM, PCB, LINE, exeption, A, 1));
Paginas[i][j].register2 = strdup(Get_R(TAM, PCB, LINE, exeption, A, 2));

Because a fixed-size array is not a pointer that can be reassigned ... now you should copy the strings:

strcpy(Get_I(TAM, PCB, LINE, exeption, A),Paginas[i][j].Instruccion);
strcpy(Get_R(TAM, PCB, LINE, exeption, A, 1),Paginas[i][j].register1);
strcpy(Get_R(TAM, PCB, LINE, exeption, A, 2),Paginas[i][j].register2);
    
answered by 26.06.2018 в 07:42