typedef struct {
uint32_t var1:
...
int8_t arrayVar[]; /* Declare as flexible array, allowed since C99 */
} dataClass;
有類似的東西分配:
data1 = malloc(sizeof (dataCLass) + DIM1*sizeof ((dataClass*)NULL)->arrayVar[0]);
data2 = malloc(sizeof (dataCLass) + DIM2*sizeof ((dataClass*)NULL)->arrayVar[0]);
or define
#define ALLOCDATA(dim) malloc(sizeof (dataCLass) + (dim)*sizeof ((dataClass*)NULL)->arrayVar[0]);
定義
#define ELEMENT1(data, i) (dataClass*)(((char*)(data))+(i)*(DIM1+sizeof (dataCLass)))
#define ELEMENT2(data, i) (dataClass*)(((char*)(data))+(i)*(DIM2+sizeof (dataCLass)))
,或者如果你參數化的DIM
#define ELEMENT(data, i, dim) (dataClass*)(((char*)(data))+(i)*((dim)+sizeof (dataCLass)))
享受
ELEMENT1(data1, i)->var1 = 1;
ELEMENT1(data1, i)->arrayVar1[9] = 4;
ELEMENT2(data2, i)->arrayVar1[14] = 4;
或
ELEMENT(data1, i, DIM1)->var1 = 1;
ELEMENT(data1, i, DIM1)->arrayVar1[9] = 4;
ELEMENT(data2, i, DIM2)->arrayVar1[14] = 4;
並不完美,但不是太怪異構建到無法使用。
編輯: 元素定義應改爲
#define ELEMENT1(data, i) (dataClass*)(((char*)(data))+(i)*(DIM1*sizeof ((dataClass*)NULL)->arrayVar[0]+sizeof (dataCLass)))
#define ELEMENT2(data, i) (dataClass*)(((char*)(data))+(i)*(DIM2*sizeof ((dataClass*)NULL)->arrayVar[0]+sizeof (dataCLass)))
#define ELEMENT(data, i, dim) (dataClass*)(((char*)(data))+(i)*((dim)*sizeof ((dataClass*)NULL)->arrayVar[0]+sizeof (dataCLass)))
這種變化,你arrayVar場可以是任何類型的,並不僅限於大小的元素1.
這聽起來像是其中一個宏可能是最合適的解決方案之一... – 2013-03-27 12:24:16
您需要着名的** struct hack!** – 2013-03-27 12:24:32
或者一個* flexible數組*,因爲它自C99以來就被稱爲。 – WhozCraig 2013-03-27 12:26:46