1
struct st1{
    int a:1; int b:3; int c:6; int d:3;
}s1;

struct st2{
    char a:3;
}s2;

int main(){
    printf("%d : %d",sizeof(s1),sizeof(s2));
    getchar();
}    

I am getting the output as 2 : 1

will you please tell me, how this program works and whats the use of : operator (a:1) here.

Thank you

borrible
  • 17,120
  • 7
  • 53
  • 75
Naveen Suman
  • 137
  • 2
  • 7
  • Your `printf` statement is not correct, a good compiler might give you a warning... The format specifier for `size_t` is `%zu`, the `z` for the size of the `size_t` and the `u` because this is an unsigned value. – Jens Gustedt Aug 18 '11 at 10:22

3 Answers3

4

The : defines a bit-field.

In your example, objects of type struct st1 use 13 bits in some arrangement chosen by the compiler.

The particular arrangement chosen when you compiled the code originated an object that occupies 2 bytes. The 13 bits are not necessarily the first (or last) in those bytes.

The other struct type (struct st2) occupies (3 bits out of) 1 byte.

pmg
  • 106,608
  • 13
  • 126
  • 198
1

The : operator used there specifies sizes in bits of the fields contained there. sizeof() return byte boundary length, so for the first, 13 bits (2 bytes), and for the second, 1 byte.

Diego Sevilla
  • 28,636
  • 4
  • 59
  • 87
0

There's at least two things worth noting here:

  1. Every object must be addressable, which means it will at least occupy the size of one char.
  2. The implementation is free to add padding for alignment or other issues as it sees fit. Iow, a struct containing two ints is not guaranteed to be equal in size to sizeof(int)*2.
harald
  • 5,976
  • 1
  • 24
  • 41