Question

I am working with bit-fields in C and do not understand what is going on with them. I created this code but I do not understand why different things are coming up as usual.

struct tB
{ 
unsigned b1:3;
signed b2:6;
unsigned b3:11;
signed b4:1;
} b;


int main(void)
{ 
struct tB *p;

printf("%d\n", sizeof(*p));
}

Why when I print out *p do I get 4 as *p?

Let us say I was trying to get sizeof(b), how would I come up with that?

Was it helpful?

Solution

sizeof(b) will give you the size in bytes of a variable of type struct tB,which in this case will be 4 (Due to padding it won't be 3 as it is expected to be)

sizeof(*p) will again give you the size in bytes of a variable of type struct tB .You should initialize p with the address of a variable of struct tB type.Eg:

struct tB *p=&b;

But you should know that in this case if you use sizeof(p) then it would give the size of the pointer p, not the variable pointed by p. Try this variation of your program :

#include<stdio.h>

struct tB
{
unsigned b1:3;
signed b2:6;
unsigned b3:11;
signed b4:1;
unsigned  b5:13;
} b;


int main(void)
{
struct tB *p;

printf("%d\n%d",sizeof(*p),sizeof(p));
}

Here is another variation that rounds the size of struct tB to 24 bits(3 bytes) as you expect,by dealing with the padding using the #pragma pack() directive,which is compiler dependent (I am using CodeBlocks on Windows).

#include<stdio.h>
#pragma pack(1)
struct tB
{
unsigned b1:3;
signed b2:6;
unsigned b3:11;
signed b4:1;

} b;


int main(void)
{
struct tB *p;

printf("%d\n%d",sizeof(*p),sizeof(p));
}

OTHER TIPS

You have 21 bits, round up to nearest int and you got 32 (i.e. 4 bytes).

It's all about processor word. The processor accessing the memory can't access it, let's say, 1 or 2 bytes. It fetching it by word. Generally, compiler makes proper aligning of structures to conform word alignment. Usually, this alignment is equal to processor architecture though the size of processor register. So, in your case you have 21-bit structure which aligned to one word. If you will adjust your structure to be, say, 33-bits long you will have 2-word alignment and in your case program will print 8.

Here the article on Wikipedia related to this Data structure alignment.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top