Блог пользователя codeforrest

Автор codeforrest, история, 6 лет назад, По-английски
I was doing this question based on output.The code is depicted below. 
struct s
{
   unsigned a:5;
   unsigned b:5;
   unsigned c:5;
   unsigned d:5;
}v={1, 2};

main()
{
    printf("size of v = %d",sizeof(v));
    return 0;
}


The output of above code is "size of v = 4". I will be glad if someone could help how we are getting this 4 as output?Thanks in advance!
  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

»
6 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Auto comment: topic has been updated by codeforrest (previous revision, new revision, compare).

»
6 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Auto comment: topic has been updated by codeforrest (previous revision, new revision, compare).

»
6 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

How exactly the memory is allocated is compiler dependent. In this case the compiler assignes the first 20 bits to the four variables, and then fills it up with 12 empty bits, just to get a nice number. Computer processors are optimized for handling 1/ 2/ 4 / 8 byte integers, so this makes more sense than creating a 3 byte type.

Btw, is it really that hard to format code in a nice way?

#include<stdio.h>

struct s { 
    unsigned a:5;
    unsigned b:5; 
    unsigned c:5;
    unsigned d:5;
} v={1, 2};
    
int main() {
    printf("size of v = %d",sizeof(v));
    return 0;
}
  • »
    »
    6 лет назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    Thanks for prompt reply! I haven't posted code in formatted way, previously.I have corrected now formatting.

»
6 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Auto comment: topic has been updated by codeforrest (previous revision, new revision, compare).

»
6 лет назад, # |
Rev. 4   Проголосовать: нравится +8 Проголосовать: не нравится

Actually if 15 bits only are needs as follows, and the bit fields are declared using unsigned short, then the sizeof operator should return 2 (bytes), i.e. 16 bits.


typedef unsigned short bitfield; struct s { bitfield a: 5; bitfield b: 5; bitfield c: 5; } v;

If the same bit fields are declared using unsigned char, then the sizeof operator should return 3 (bytes), i.e. 24 bits, as the three bit fields are aligned to three consecutive bytes.

Check the output of the following test program


typedef unsigned char bitfield; struct s { bitfield a: 5; bitfield b: 5; bitfield c: 5; } v; union t { s x; unsigned char y[ 3 ]; write() const { for( int i = 0; i < 3; i++ ) cout << int( y[ i ] ) << ' '; cout << endl; } } w; int main() { ios_base::sync_with_stdio( false ), cin.tie( nullptr ), cout.tie( nullptr ); cout << "size of v = " << sizeof( v ) << endl; cout << "size of w = " << sizeof( w ) << endl; w.write(), w.x.a = 1, w.write(), w.x.b = 1, w.x.a = 0, w.write(), w.x.c = 1, w.x.b = 0, w.write(); }