Though using sizeof will include overhead and padding. Also, the problem with these kinds of questions is that some data types you don't know how long they are, for example long - its at least 4 bytes, though it could be 8 bytes (and is on my compiler).
So you are saying the total with out overhead is 43. By the way what is Overhead and padding?
Do not go by the values giblet put in. Some of the values are compiler dependent, it is far better for you to find the values your compiler is using with sizeof().
I ran the code above my outputs were
1 2 3 4 5
30
8
4
1
48
Note: These are based on my compiler, but as you can see the struct is more than the sum of the 4 variables within, I guess this is the overhead and/or padding.
Thanks everyone for your information. It was very informative. I ran the sizeof in my code and got the same thing CodeGoggles got. I appreciate everything!
Compilers will supply pad bytes (unused or filler bytes) in order to provide optimum alignment of data items for machine instructions. If we looked at that struct in memory we would see:
1 2 3 4 5 6 7 8
struct Part
{ char Description[30]; //0-29
char filler_0[2]; //30-31 pad out to 32 bytes
double Cost; //32-39 8 byte item on 8 byte boundary
long ID; //40-43 4 byte item also on 8 byte boundary
char Type; //44 doesn't need to be on an 8 byte boundary
char filler_1[3]; //45-47 pad out to multiple of 8
};
Insertion of pad characters is very machine (and even compiler) dependent, which is why it is not portable to write the struct to a file using sizeof(struct) to determine the length.
Thanks for the clarification AbstractionAnon :P. I was unsure of this myself. I can see now that it is similar to constant buffers in directX where memory is arranged in multiples of 16 bytes.
Is there any particular rule one can use to calculate this?
No, not really, because all computers have different architectures, different compilers might optimize differently, and different settings on the compiler might change the memory layout as well. If you know all of these factors it might be possible, but by then you may as well just use sizeof with those settings and be done with it.