how to calculate size of a struct?

vql's Avatar, Join Date: Sep 2007
vql
Go4Expert Member
I declare a struct:

struct ABC
{
int a;
int b;
char c;
in d;
}

I use VC++ compiler.
In main, I call function sizeof(ABC) and it returns 16. Why? Because I think sizeof(ABC) = sizeof(int) + sizeof(int) + sizeof(char) + sizeof(int) = 4+4+1+4 = 13.

What happened?
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
It returns 16 because of the compiler using the packaging format.

I would try to explain.

When you have data type which holds the maximum chunk of byte it allocates the other smaller byte as a multiple of the highest possible bytes taken for optimization of the memory and nowadays memory is quite cheap.

Try putting a float and or a double and see how the things change.
0
vql's Avatar, Join Date: Sep 2007
vql
Go4Expert Member
Thank alot. I will try. I sent a message to you about uml tool you are using. Please see it in the picture:
http://www.go4expert.com/images/arti...rn/Visitor.png

I am learning Design Pattern. Thanks.
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Its the class diagram option available in MS VC 2005
0
vql's Avatar, Join Date: Sep 2007
vql
Go4Expert Member
Quote:
Originally Posted by shabbir
It returns 16 because of the compiler using the packaging format.

I would try to explain.

When you have data type which holds the maximum chunk of byte it allocates the other smaller byte as a multiple of the highest possible bytes taken for optimization of the memory and nowadays memory is quite cheap.

Try putting a float and or a double and see how the things change.
With your answer, 3 remaining bytes will be used for what?

With 16 bytes, you can tell me the position of struct's members. Example: a from byte 0->byte 3, ... Please continue to explain for me clearly.

Why the compiler use this calculation way? Thanks.
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Nothing.
0
DaWei's Avatar, Join Date: Dec 2006
Team Leader
You can choose to pack the struct so that it uses the number of bytes you think it should use, rather than aligning members on certain boundaries. In doing so you will cause a failure on systems that do not allow access on every byte boundary (Bus Fault). If you are not intimately familiar with your implementation, you will do well to accept the compiler's safer arrangement, despite the loss of a couple bytes of memory.
0
vql's Avatar, Join Date: Sep 2007
vql
Go4Expert Member
I can't understand clearly. I am reading about option /Zp in Visual C++ Compiler. Maybe I will give myseft some examples to understand about this. Thanks.