-
question about struct
I think it very easy but it makes me confused
Code:
struct Fileheader
{
unsigned short Type; // BM Identifier
unsigned long Size; // total length in bytes
unsigned short Reserved1; // image id or revision
unsigned short Reserved2;
unsigned long OffBits;// offset to start of actual pixel data
Fileheader()
{
Reserved1=0;
Reserved2=0;
}
};
int main()
{
cout<<sizeof(Fileheader)<<endl;
}
The Output is 16 <---2+4+2+2+4=??
I can't believe so I check again
Code:
struct Fileheader
{
unsigned short Type; // BM Identifier
unsigned short Size; // total length in bytes
unsigned short Reserved1; // image id or revision
unsigned short Reserved2;
unsigned long OffBits;// offset to start of actual pixel data
Fileheader()
{
Reserved1=0;
Reserved2=0;
}
};
int main()
{
cout<<sizeof(Fileheader)<<endl;
}
The output is 12=2+2+2+2+4...accurate but:confused:
So it means that we can't have a struct having size of 14??
-
>So it means that we can't have a struct having size of 14??
It depends on how your implementation aligns memory as well as how structures are padded to meet those alignment requirements.
-
You mean that b/c of I'm out of memory??I don't think so
I want to load bitmap file into my program so the struct must have the length enough.
so anyone can explain me
-
>You mean that b/c of I'm out of memory??
No, I don't. I mean that structures are padded for alignment reasons. This changes the size of the structure instances. That is why you don't get the size that you expect and cannot get the size that you want. If your code requires that the size of a structure instance be 14 bytes, you must read the file manually and assign your input to the correct member.
-
Depending on your compiler, you could try
Code:
#pragma pack(1)
struct Fileheader
{
unsigned short Type; // BM Identifier
unsigned short Size; // total length in bytes
unsigned short Reserved1; // image id or revision
unsigned short Reserved2;
unsigned long OffBits;// offset to start of actual pixel data
};
#pragma pack()