All pastes #162961 Raw Edit

Something

public text v1 · immutable
·published 2006-09-07 00:35 UTC
rendered paste body
/* Luis R. Rodriguez <mcgrof@gmail.com> 
 * Demonstrate nested zero-length array mess */

#include <stdio.h>
#include <stdlib.h>

#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))

struct planet {
        unsigned int planet_id;
        unsigned int number_of_creatures;
};

struct god {
        unsigned int god_id;
        unsigned int num_planets;
        struct planet planets[0];
};

struct universe {
        unsigned int universe_id;
        struct god gods[2]; /* lets assume there are only 2 gods */
};

void print_universe(struct universe *);
void print_universe(struct universe *u)
{
        int i,j;
        printf("In this universe...\n", u->universe_id);
        for(i=0; i < ARRAY_SIZE(u->gods); i++) {
                printf("\tGod (%d) reigns on these worlds:\n", u->gods[i].god_id);
                printf("\t\tplanet_id\tnumber_of_creatures\n");
                for(j=0; j < u->gods[i].num_planets; j++){
                        printf("\t\t%d\t\t%d\n", u->gods[i].planets[j].planet_id,
                                        u->gods[i].planets[j].number_of_creatures);
                }
        }
}

int main()
{ 
        unsigned int num_planets = 9;
        int i,j;

        struct universe *u = malloc(sizeof(struct universe) + 
                        (sizeof(struct planet) * num_planets));

        u->universe_id = 1;

        u->gods[0].god_id = 0;
        u->gods[0].num_planets= 9;

        u->gods[1].god_id = 1;
        u->gods[1].num_planets= 90;

        for(i=0; i<2; i++) {
                for(j=0; j < u->gods[i].num_planets; j++){
                        u->gods[i].planets[j].planet_id = j;
                        u->gods[i].planets[j].number_of_creatures = j^2;
                }
        }
        print_universe(u);
        return 0;
}