一、零長數組數組
GNU C容許聲明長度爲零的數組,但它只能被用於結構體的最後一個成員。this
實例:spa
#include <stdio.h> #include <stdlib.h> typedef struct pos { double lon; double lat; }tPos; struct line { int length; tPos pos[0]; }; int main(void) { int i, count = 9; struct line *thisline = (struct line *)malloc(sizeof(int) + sizeof(tPos)* count + 1); thisline->length = count; for (i = 0; i < count; i++) { thisline->pos[i].lon = 121.175581 - i; thisline->pos[i].lat = 31.567345 + i; } printf("sizeof(struct line) = %d\n", sizeof(struct line)); for (i = 0; i < thisline->length; i++) { printf("thisline->pos[%d].lon = %f\n", i,thisline->pos[i].lon); printf("thisline->pos[%d].lat = %f\n", i,thisline->pos[i].lat); } return 0; }
輸出:code
sizeof(struct line) = 8
thisline->pos[0].lon = 121.175581
thisline->pos[0].lat = 31.567345
thisline->pos[1].lon = 120.175581
thisline->pos[1].lat = 32.567345
thisline->pos[2].lon = 119.175581
thisline->pos[2].lat = 33.567345
thisline->pos[3].lon = 118.175581
thisline->pos[3].lat = 34.567345
thisline->pos[4].lon = 117.175581
thisline->pos[4].lat = 35.567345
thisline->pos[5].lon = 116.175581
thisline->pos[5].lat = 36.567345
thisline->pos[6].lon = 115.175581
thisline->pos[6].lat = 37.567345
thisline->pos[7].lon = 114.175581
thisline->pos[7].lat = 38.567345
thisline->pos[8].lon = 113.175581
thisline->pos[8].lat = 39.567345blog
注意:在分配空間大小時,須要分配足夠的大小,不然結果可能爲隨機數據;io
跨平臺使用時,不必定可移植class