bit fields - Questions about C bitfields -


  • is bitfield c concept or c++?

  • can used within structure? other places can use them?

  • afaik, bitfields special structure variables occupy memory specified no. of bits. useful in saving memory , nothing else. am correct?

i coded small program understand usage of bitfields - but, think not working expected. expect size of below structure 1+4+2 = 7 bytes (considering size of unsigned int 4 bytes on machine), surprise turns out 12 bytes (4+4+4). can let me know why?

#include <stdio.h>  struct s{ unsigned int a:1; unsigned int b; unsigned int c:2; };  int main() {   printf("sizeof struct s = %d bytes \n",sizeof(struct s));   return 0; } 

output:

sizeof struct s = 12 bytes  

because a , c not contiguous, each reserve full int's worth of memory space. if move a , c together, size of struct becomes 8 bytes.

moreover, telling compiler want a occupy 1 bit, not 1 byte. though a , c next each other should occupy 3 bits total (still under single byte), combination of a , c still become word-aligned in memory on 32-bit machine, hence occupying full 4 bytes in addition int b.

similarly, find that

struct s{ unsigned int b; short s1; short s2; }; 

occupies 8 bytes, while

struct s{ short s1; unsigned int b; short s2; }; 

occupies 12 bytes because in latter case, 2 shorts each sit in own 32-bit alignment.


Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -