Linux c:零长数组
1、零长数组
GNU C允许声明长度为零的数组,但它只能被用于结构体的最后一个成员。
实例:
#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; }
输出:
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.567345
注意:在分配空间大小时,需要分配足够的大小,否则结果可能为随机数据;
跨平台使用时,不一定可移植