Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   how to calculate size of a struct? (http://www.go4expert.com/forums/calculate-size-struct-t6570/)

 vql 27Sep2007 20:53

how to calculate size of a struct?

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?

 shabbir 27Sep2007 21:08

Re: how to calculate size of a struct?

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.

 vql 27Sep2007 21:21

Re: how to calculate size of a struct?

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.

 shabbir 27Sep2007 21:46

Re: how to calculate size of a struct?

Its the class diagram option available in MS VC 2005

 vql 12Oct2007 20:46

Re: how to calculate size of a struct?

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.

 shabbir 12Oct2007 22:16

Re: how to calculate size of a struct?

Nothing.

 DaWei 12Oct2007 22:49

Re: how to calculate size of a struct?

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.

 vql 13Oct2007 15:40

Re: how to calculate size of a struct?

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.

 All times are GMT +5.5. The time now is 23:00.