在分析某代码时,发现某结构体定义为
typedef struct _BUSENUM_PLUGIN_HARDWARE
{
//
// sizeof (struct _BUSENUM_HARDWARE)
//
__in ULONG Size;
//
// Unique serial number of the device to be enumerated.
// Enumeration will be failed if another device on the
// bus has the same serail number.
//
__in ULONG SerialNo;
//
// An array of (zero terminated wide character strings). The array itself
// also null terminated (ie, MULTI_SZ)
//
__in WCHAR HardwareIDs[];
} BUSENUM_PLUGIN_HARDWARE, *PBUSENUM_PLUGIN_HARDWARE;
最开始以为sizeof(BUSENUM_PLUGIN_HARDWARE)等于12,因为我认为WCHAR HardwareID[]等效于WCHAR HardwareID[1]。但具体测试时发现其结构体大小为8,即结构体不包含最后一个成员,并且应用层编译器会有警告:
warning C4200: 使用了非标准扩展 : 结构/联合中的零大小数组
1> 当 UDT 包含大小为零的数组时,无法生成复制构造函数或副本赋值运算符
如果在结构体附加一个成员(需要内存空间或者另外一个大小为零的数组)
typedef struct _BUSENUM_PLUGIN_HARDWARE
{
//
// sizeof (struct _BUSENUM_HARDWARE)
//
__in ULONG Size;
//
// Unique serial number of the device to be enumerated.
// Enumeration will be failed if another device on the
// bus has the same serail number.
//
__in ULONG SerialNo;
//
// An array of (zero terminated wide character strings). The array itself
// also null terminated (ie, MULTI_SZ)
//
__in WCHAR HardwareIDs[];
//__in WCHAR Name[];
__in ULONG ulRear;
} BUSENUM_PLUGIN_HARDWARE, *PBUSENUM_PLUGIN_HARDWARE;
编译器会报告错误:
error C2229: struct“_BUSENUM_PLUGIN_HARDWARE”有非法的大小为零的数组
所以,一个结构体可以包含一个大小为0的数组,但是必须处于结构体末尾,并且其不占用结构体内存空间。