我會讓matr
一個靈活的數組在結尾。然後,我會將arr
陣列粘貼到matr
的最後一行。
typedef struct {
int size;
int var1, var2;
int matr[];
} s;
static inline int size_ok_s (int size) {
switch (size) {
case SIZE_A:
case SIZE_B:
return 1;
default:
break;
}
return 0;
}
s * create_s (int size) {
s *x = 0;
if (size_ok_s(size)) {
x = malloc(sizeof(*x) + sizeof(int[size+1]));
if (x) x->size = size;
}
return x;
}
爲了實現一個統一的接口,你可以使用宏:
#define s_matr(x) ((int (*)[(x)->size])(size_ok_s((x)->size) ? (x)->matr : 0))
#define s_arr(x) (s_matr(x)[(x)->size])
因此,訪問i
日行j
日s *foo
的matr
的列,其k
tharr
的元素:
s *foo = create_s(SIZE_A);
/* ... */
s_matr(foo)[i][j] = 0;
s_arr(foo)[k] = 0;
名
彈性陣列成員是在§ 6.7.2.1 ¶ 16描述的C.99一個新功能之前C.99,經常使用C程序員什麼被稱爲struct
劈:
typedef struct {
int size;
int var1, var2;
int matr[1];
} s;
s * create_s (int size) {
s *x = 0;
if (size_ok_s(size)) {
x = malloc(sizeof(*x) + sizeof(int[size]));
if (x) x->size = size;
}
return x;
}
從C.89-90開始,這是一個黑客技術,對matr
數組進行索引的值大於0
,它在技術上訪問超出其邊界的對象。然而,這是一種常見的做法,並且具有廣泛的便攜性。 C.99正式批准了靈活數組成員的機制,儘管它需要在數組聲明中沒有指定大小的語法。
來源
2013-07-30 23:13:27
jxh
如果內存不連續,你關心嗎? – Magn3s1um
不,沒有特別的限制。 – lukmac