Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

actual structure size

How can I know the actual structure size? using sizeof returns the number of bytes after alignment. For example :

struct s {
               char c;
               int i
}

sizeof(s) = 8; I am interested to get the size of bytes without alignment ,i.e 5

like image 508
Yakov Avatar asked Dec 27 '22 18:12

Yakov


1 Answers

The actual size of structure is size of structure after alignment. I mean sizeof return size of structure in the memory. if you want to have an structure that aligned on byte you should tell the compiler to do that. for example something like this:

#ifdef _MSVC
#  pragma pack(push)
#  pragma pack(1)
#  define PACKED
#else
#  define PACKED            __attribute((packed))
#endif
struct byte_aligned {
    char c;
    int i;
} PACKED;
#ifdef _MSVC
#  pragma pack(pop)
#endif

now sizeof(byte_aligned) return 5 and its actually 5 byte in memory

like image 180
BigBoss Avatar answered Jan 17 '23 16:01

BigBoss