C-struct occupies more memory space than the sequence of its members

Asked

Viewed 19 times

0

No 1° example a struct occupies 16bytes:

#include <Studio.h>

int main()
{

   struct horario{
      int hora;
      int minuto;
      int *h;
    };

   struct horario agora;
   
   int tamanho = sizeof(agora);

   printf("%d bytes\n", tamanho);
   //16 bytes

   return 0;
}

Why when I change the members of struct it stops occupying 16bytes and starts occupying 24bytes?

#include <Studio.h>

int main()
{

/*trocando posição dos membros da struct, o ponteiro *h fica no 2° membro e minuto vai para o 3°:*/

   struct horario{
      int hora;
      int *h;
      int minuto;
    };

   struct horario agora;
   
   int tamanho = sizeof(agora);

   printf("%d bytes\n", tamanho);
   //24 bytes

   return 0;
}

  • Search by "padding". Some compilers require that the variable, depending on the type of data, be allocated to an address that is multiple of 2.4, ..

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.