Click to See Complete Forum and Search --> : Regarding structure size


seshreddy
April 23rd, 2003, 07:50 AM
#include <iostream.h>
hi,

I want to use structure for reprentation of bits and do not want
maximum size of integer.

here I have given the code and it is giving out put for size of structure as 4 bytes.

but how can i get exact size what i am using.


struct packet
{
int FC :8;
int DS :4;
};

int main()
{
packet pack;

cout<<"size ofpacket"<<sizeof(pack)<<endl;
pack.FC=124;
pack.DS=15;
cout<<"pack.FC="<<pack.FC<<endl;
cout<<"pack.DS="<<pack.DS<<endl;
cout<<sizeof(packet);

return 0;
}


please hel p me..

bye
seshu

dimm_coder
April 23rd, 2003, 08:07 AM
For setting an alligment of structure in memory use:
#pragma pack(push, _size_)
struct name_t
{
...
};
...
#pragma pack(pop)

where _size_ is a const value of alligment in bytes.
So in your case use _size_=2

Graham
April 23rd, 2003, 08:12 AM
or you could try:

struct packet
{
char FC : 8;
char DS : 4;
};

You won't get the size less than 2, though (assuming 8-bit bytes).

dimm_coder
April 23rd, 2003, 08:19 AM
Originally posted by Graham
or you could try:

struct packet
{
char FC : 8;
char DS : 4;
};

You won't get the size less than 2, though (assuming 8-bit bytes).

Even in this case U need to use #pragma pack () , because default system aligment for some compiler can have a some fixed value. Default ussually = 4 bytes. So every struct will be rounded to 4-bytes boundary by default.

Graham
April 23rd, 2003, 09:33 AM
True, true.......

seshreddy
April 23rd, 2003, 09:40 AM
thank you..

as u told depends on compiler size of data type varies.

bye
seshu