c++ - Why is this struct size 3 instead of 2? -



c++ - Why is this struct size 3 instead of 2? -

i have defined struct:

typedef struct { char a:3; char b:3; char c:3; char d:3; char e:3; } col;

the sizeof(col) give me output of 3, shouldn't 2? if comment 1 element, sizeof 2. don't understand why: 5 element of 3 bits equal 15 bits, , that's less 2 bytes.

is there "internal size" in defining construction one? need clarification, because notion of language far, expected size of 2 byte, not 3.

because using char underlying type fields, compiler tries grouping bits bytes, , since cannot set more 8 bits in each byte, can store 2 fields per byte.

the total sum of bits struct uses 15, ideal size fit much info short.

#include <stdio.h> typedef struct { char a:3; char b:3; char c:3; char d:3; char e:3; } col; typedef struct { short a:3; short b:3; short c:3; short d:3; short e:3; } col2; int main(){ printf("size of col: %lu\n", sizeof(col)); printf("size of col2: %lu\n", sizeof(col2)); }

the above code (for 64-bit platform mine) indeed yield 2 sec struct. larger short, struct fill no more 1 element of used type, - same platform - struct end size 4 int , 8 long, etc.

c++ c struct

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -