Click to See Complete Forum and Search --> : How to determine the return value of sizeof(struct ...)


zyt
November 1st, 2001, 01:17 PM
I have created a struct which is composed of a char and a short. But the return value of sizeof( this struct) is 4 while I expect it to be 3. If I add a short, the the return value is 6.

Is there a way to accurately predict the result of sizeof(struct or class)? Thanks!

signature

easye21
November 1st, 2001, 01:38 PM
The reason for it is the compiler sets things in memory 4 bytes apart since it increases performance. I don't know what you should do unless you add size of's for each member and get a total.

zyt
November 1st, 2001, 01:46 PM
Thanks. I want to copy data from a byte buffer to an instance of this struct. If the bytes copied is too large, it may flush the memory. If I used a constant size, the next time I change the struct I'll have to change all the places this copy is performed.

signature

James Curran
November 1st, 2001, 02:51 PM
The value of sizeof correct (and it's not really a "return value" since sizeof is an operator, not a function)

Give the struct:struct ABC
{
char a;
short b;
};

You may think the size should be 3, but it's really 4. The difference is important when you do something like:Strct ABC abc[4];

Here, &abc[1] starts 4 bytes from &abc[0].

Most compilers have a way to allow you to force them to not align data (so that, for example, struct ABC really would be 3 bytes). For MS VC++, it's #pragma pack(1). For other compiler, you'll have to check their documentation.


Truth,
James
http://www.NJTheater.com
http://www.NovelTheory.com
I don't do it for the points (OK, maybe I do), but rating a post is a good way for me to know if I helped.