2013-11-22 75 views
0

我使用多個程序員之間共享文件,該文件有這樣的結構:如何使用結構與位域

typedef struct _APPLE{ 
    ULONG appleID; 
    struct{ 
     ULONG isBig: 1; 
     ULONG isRed: 1; 
     ULONG isFresh: 1; 
     ULONG isGood: 1; 
     ULONG bReserved: 28; 
    }; 
}APPLE; 

當文件共享我不能編輯它。我想用這個APPLE結構我代碼並希望爲其每個成員提供值。我怎樣才能做到這一點?

+0

什麼是你正面臨着創建它的實例的問題?蘋果是否有任何問題? a.isBig = 0;'? – Sadique

+0

我可以做到這一點。但是當我這樣做a.isBig = 0;內存是否像工會一樣共享,或者我可以分別爲每個成員分配值? –

+0

不可以。創建它自己的對象。 – Sadique

回答

2

首先,你不能在標準C中擁有匿名嵌套結構,它是一些編譯器使用的擴展。

所以,你必須命名位字段結構:

typedef struct _APPLE{ 
    ULONG appleID; 
    struct{ 
     ULONG isBig: 1; 
     ULONG isRed: 1; 
     ULONG isFresh: 1; 
     ULONG isGood: 1; 
     ULONG bReserved: 28; 
    } flags; 
}APPLE; 

然後,只需使用普通的點號來使用領域:

APPLE apple; 
apple.appleID = 5; 
apple.flags.isBig = 1; 
apple.flags.isRed = 0; 

雖然的多個成員位字段可能共享相同的int,它們仍然彼此分開。所以改變位域的一個成員不會改變任何其他成員。

+0

我使用的是Visual Studio 2012,我認爲它在這裏支持。 becoz其他程序員正在使用它。 –

0

根據ISO/IEC 9899:2011,部分§6.7.2.1結構和聯合說明

An implementation may allocate any addressable storage unit large enough to hold a bitfield. If enough space remains, a bit-field that immediately follows another bit-field in a structure shall be packed into adjacent bits of the same unit. If insufficient space remains, whether a bit-field that does not fit is put into the next unit or overlaps adjacent units is implementation-defined. The order of allocation of bit-fields within a unit (high-order to low-order or low-order to high-order) is implementation-defined. The alignment of the addressable storage unit is unspecified.