zoukankan      html  css  js  c++  java
  • 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
    ", sizeof(struct line));
        
        for (i = 0; i < thisline->length; i++)
        {
            printf("thisline->pos[%d].lon = %f
    ", i,thisline->pos[i].lon);
            printf("thisline->pos[%d].lat = %f
    ", 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

    注意:在分配空间大小时,需要分配足够的大小,否则结果可能为随机数据;

    跨平台使用时,不一定可移植

  • 相关阅读:
    HDU 1240 Asteroids!【BFS】
    POJ 2251 Dungeon Master【BFS】
    HDU 1548 A strange lift【BFS】
    HDU 1171 Big Event in HDU【01背包】
    HDU 1505 City Game【DP】
    POJ 2386 Lake Counting【BFS】
    POJ 3278 Catch That Cow【BFS】
    HDU 1506 Largest Rectangle in a Histogram【DP】
    随想而已
    HDU 1285 确定比赛名次【拓扑排序】
  • 原文地址:https://www.cnblogs.com/Pan-Z/p/11528053.html
Copyright © 2011-2022 走看看