阅读:1473回复:6
数据结构长度执行时跟定义的不一致,为什么??
我定义了两个结构:
#define LENGTHOFFILENAME 255 #define TOTALFILENUM 30 typedef struct tagFILEACLENTRY { CHAR FileName[LENGTHOFFILENAME]; UCHAR nFileProperity; } FILEACLENTRY,*PFILEACLENTRY; typedef struct tagFILEACL { DWORD nChekSum; UCHAR nAreaNum; UCHAR nComputerNum; DWORD CardSerialNum; DWORD nFileNum; DWORD nReserved; FILEACLENTRY FileAcl[TOTALFILENUM]; }FILEACL,*PFILEACL; 这里FILEACL结够应该是4+1+1+4+4+4+(255+1)*30=7698(bytes)。 但是我在调试中发现sizeof(FILEACL)==7700!!! 多了两个字节,这是怎么啦?? |
|
沙发#
发布于:2005-05-08 10:26
We can take an experiment in the VC6.0 enviroment: 确实是个问题:) VC设置中的N字节对齐就是说变量存放的起始地址的偏移量有两种情况:第一、如果n大于等于该变量所占用的字节数,那么偏移量必须满足默认的对齐方式,第二、如果n小于该变量的类型所占用的字节数,那么偏移量为n的倍数,不用满足默认的对齐方式。 结构的总大小也有个约束条件,分下面两种情况:如果n大于所有成员变量类型所占用的字节数,那么结构的总大小必须为占用空间最大的变量占用的空间数的倍数;否则必须为n的倍数。 在这种情况下,由于上面的结构中最大变量占用的空间数为4字节,对于8字节和16字节来说,情况是相同的,即结构的总大小必须为占用空间最大的变量占用的空间数(现在是4)的倍数。 |
|
板凳#
发布于:2005-04-30 15:44
我已经解决了,是编译时对齐方式造成的。
结构typedef struct tagFILEACL { DWORD nChekSum; UCHAR nAreaNum; UCHAR nComputerNum; DWORD CardSerialNum; DWORD nFileNum; DWORD nReserved; FILEACLENTRY FileAcl[TOTALFILENUM]; }FILEACL,*PFILEACL; 中DWORD nChekSum后面只有两个UCHAR变量,由于vc->setting->c/c++->Code Generation->Struct member alignment设置的是“8 Bytes *”,编译是会在UCHAR设置的变量处补齐。 或者把vc->setting->c/c++->Code Generation->Struct member alignment设置的是“1 Bytes *”, 或者更改结构为 typedef struct tagFILEACL { DWORD nChekSum; UCHAR nAreaNum; UCHAR nComputerNum; UCHAR nReserved[2]; DWORD CardSerialNum; DWORD nFileNum; FILEACLENTRY FileAcl[TOTALFILENUM]; }FILEACL,*PFILEACL; 可以解决此问题!!! :D :D :D :D :D :D :D :D :D :D |
|
地板#
发布于:2005-04-30 11:57
我定义了两个结构: 将结构这样定义应该就可以了,简单的边界对齐问题: typedef struct tagFILEACL { DWORD nChekSum; DWORD CardSerialNum; DWORD nFileNum; DWORD nReserved; UCHAR nAreaNum; UCHAR nComputerNum; FILEACLENTRY FileAcl[TOTALFILENUM]; }FILEACL,*PFILEACL; |
|
地下室#
发布于:2005-04-29 10:16
We can take an experiment in the VC6.0 enviroment:
Press Alt+F7, then jump \"Project Setting\", Click to the page \"C/C++\", choose the \"Category\", Change the \"Struct member alignment\", when choose \"1 byte\" or \"2 bytes\", the sizeof(FileAcl) = 7698; When choose \"4 bytes\" or \"8 bytes *\" or \"16 bytes\", sizeof(FileAcl) = 7700. The default setting of \"Struct member aliment\" is 8 bytes. From the above exprement, we can see the alignment format affect the size of structure. But there are another question: Why when we set the \"Struct member aliment\" to \"8 bytes\" or \"16 bytes\", the sizeof FILEACL is still 7700. As the rule, when the \"Struct member aliment\" is 8 bytes, it should 7704; when the \"Struct member aliment\" is 16 bytes, it should 7712. Why? Who can explain it? Thanks! My msn: jgw2008@hotmail.com |
|
|
5楼#
发布于:2005-04-29 09:23
一般都是按字对齐的
|
|
|
6楼#
发布于:2005-04-29 08:14
这个和字节对齐有关,如果不够会自动补充字节,具体有一些规则
定义时最好把同类型或同大小的放到一起 |
|
|