谢谢, 我认为这是工会问题 再见 "路" < LR ***** @ yahoo.com>写道:Visula C ++ 6.0中的我已经声明了这样的结构: typedef struct _WRITE_INPUT { 不要使用以下划线开头的标识符;他们保留了实施的。 (它稍微复杂一些,但它只是为了避免它们而是最安全的。) ULONG DeviceNumber; ULONG RegisterNumber; USHORT ShortData; UCHAR CharData; }; } WRITE_INPUT; 我无法理解为什么,sizeof( WRITE_INPUT)返回12.它应该返回10,不应该吗? sizeof(ULONG)= 4 sizeof(ULONG)= 4 sizeof( USHORT)= 2(最长的联合字段) 4 + 4 + 2 = 10 编译器可以在任何成员之后添加填充结构。 在这种情况下,它可能在末尾添加2个字节的填充 使结构的大小为4的倍数,所以如果您有一系列结构,ULONG成员 将正确对齐。 顺便提一下,名称ULONG,USHORT和UCHAR并不是特别的 很有帮助。我认为它们分别是unsigned long, unsigned short和unsigned char的typedef(或宏?)。为什么不直接使用 名字? - Keith Thompson(The_Other_Keith) ks *** @ mib.org < http://www.ghoti.net/~kst> 圣地亚哥超级计算机中心< * GT; < http://users.sdsc.edu/~kst> 我们必须做点什么。这是事情。因此,我们必须这样做。 hi,in Visula C++ 6.0 I have declared a struct like this:typedef struct _WRITE_INPUT {ULONG DeviceNumber;ULONG RegisterNumber;union {USHORT ShortData;UCHAR CharData;};} WRITE_INPUT;I can''t understand why, sizeof(WRITE_INPUT) returns 12. It shouldreturn 10, shouldn''t it?sizeof(ULONG) = 4sizeof(ULONG) = 4sizeof(USHORT) = 2 (longest union field)4 + 4 + 2 = 10thanksbyeluke 解决方案 luke wrote: hi, in Visula C++ 6.0 I have declared a struct like this: typedef struct _WRITE_INPUT { ULONG DeviceNumber; ULONG RegisterNumber; union { USHORT ShortData; UCHAR CharData; }; } WRITE_INPUT; I can''t understand why, sizeof(WRITE_INPUT) returns 12. It should return 10, shouldn''t it? sizeof(ULONG) = 4 sizeof(ULONG) = 4 sizeof(USHORT) = 2 (longest union field) 4 + 4 + 2 = 10 thanks bye lukec.l.c FAQ #2.13 would answer your questionthank you,I thought it was a union problembye "luke" <lr*****@yahoo.com> writes: in Visula C++ 6.0 I have declared a struct like this: typedef struct _WRITE_INPUT {Don''t use identifiers starting with an underscore; they''re reserved tothe implementation. (It''s slightly more complex than that, but it''ssafest just to avoid them.) ULONG DeviceNumber; ULONG RegisterNumber; union { USHORT ShortData; UCHAR CharData; }; } WRITE_INPUT; I can''t understand why, sizeof(WRITE_INPUT) returns 12. It should return 10, shouldn''t it? sizeof(ULONG) = 4 sizeof(ULONG) = 4 sizeof(USHORT) = 2 (longest union field) 4 + 4 + 2 = 10The compiler is free to add padding after any member of a structure.In this case, it''s probably adding 2 bytes of padding at the end tomake the size of the structure a multiple of 4, so the ULONG memberswill be aligned properly if you have an array of structures.Incidentally, the names ULONG, USHORT, and UCHAR aren''t particularlyhelpful. I presume they''re typedefs (or macros?) for unsigned long,unsigned short, and unsigned char, respectively. Why not just use thenames directly?--Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>We must do something. This is something. Therefore, we must do this. 这篇关于包含联合的结构的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-19 15:38