|
-
October 4th, 2002, 06:54 AM
#1
sizeof question
I'm at a lost on why the sizeof NODE per call below is 8.
My thoughts are it should be 5. considering the sizeof NODESTATE is 4 and the sizeof unsigned char is 1. Why is it 8?
Code:
# include <iostream>
using namespace std;
typedef enum
{
NOT_PRESENT = 0u,
POWER_OFF,
POWER_ON,
SILENT
} NODESTATE;
typedef struct
{
unsigned char address;
NODESTATE state;
} NODE;
static NODE NodeMap [] =
{
0, NOT_PRESENT,
0, NOT_PRESENT
// 0, NOT_PRESENT
};
int main(void)
{
printf( "%s%d\n", "sizeof NodeMap = ", sizeof(NodeMap));
printf( "%s%d\n", "sizeof NODE = ", sizeof(NODE));
printf( "%s%d\n", "sizeof unsigned char = ", sizeof(unsigned char));
printf("%d\n",sizeof(NODESTATE));
return 0;
}
RESULT :
sizeof NodeMap = 16
sizeof NODE = 8
sizeof unsigned char = 1
4
-
October 4th, 2002, 07:45 AM
#2
Probably because the compiler is aligning your structures on a 4-byte boundary.
Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
-- Sutter and Alexandrescu, C++ Coding Standards
Programs must be written for people to read, and only incidentally for machines to execute.
-- Harold Abelson and Gerald Jay Sussman
The cheapest, fastest and most reliable components of a computer system are those that aren't there.
-- Gordon Bell
-
October 4th, 2002, 08:09 AM
#3
The size is different from five since the compiler will align this structure. This is called structure alignment. Fundamental types (int, float etc.) are stored in memory at addresses that are multiples of their length. CPU are optimized to access memory aligned this way. The compiler will therefore add some extra bytes between the fields of a structure to ensure that all of them that require alignment are properly aligned. Same applies to the instances of that structure. Therefore the compiler might add also some extra bytes at the end to ensure that arrays of this structure also get aligned properly.
The whole thing is based on the implementation, meaning that every compiler vendor is free to use the way of alignment and padding to fit their compiler the best. So you cannot rely on a standard alignment. Visual C++ compilers traditionally use 8-byte alignment as the standard value. Others might only use 4-byte alignment.
Nevertheless, that is why the size of your structure differs from your calculated one...
-
October 4th, 2002, 08:17 AM
#4
If you are using VC++, try adding #pragma pack(n) where n can be 1, 2, 4,8, 16. The results vary a lot.
Succinct is verbose for terse
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|