Zero Length Arrays Allowed in C Standard?

Ray Butterworth rbutterworth at watmath.waterloo.edu
Sat Dec 2 05:05:21 AEST 1989


In article <11715 at smoke.BRL.MIL> gwyn at brl.arpa (Doug Gwyn) writes:
>I'm POC for a zero-sized object special interest group,
>but frankly there has been little activity since the
>committee's consensus was clearly against such objects.
>
>You might consider changing the [0]s to [1]s and where
>the allocation/pointer trickery occurs in the code
>making an adjustment for the additional byte in the
>object type.

That of course leads to problems if anyone does
    s = (Structure *)malloc(sizeof(Structure));
without knowing about this special kludge in the definition,
or if anyone does any of the other things that are now being discussed
in comp.std.unix about the problems associated with the structure
in <dirent.h>.

====

If you want a suggestion for your SIG, has this been thought of before?
(probably only a few hundred times)

If object[0] were made legal, it should have the restriction
that its size can never be known by the compiler.
i.e. sizeof(object) should never be 0.
This implies that if it appears in a structure it must be the last member,
and the size restriction is inherited by that structure.
(sort of like how incomplete types are ok if you don't do anything with them.)

    typedef struct { int x; int y[]; } Struct;
    Struct *p;
would make each of these six lines illegal:
    auto int y[0];
    static Struct s;
    func(s)
    malloc(sizeof(Struct))
    ++p
    p[NON_ZERO]
since all of these require the size of the object.

One could of course have
    extern Struct s;
    extern int z[0];
    func(s, &s, p->x, &s.y[0], s.y);
since the size isn't needed.

That would solve the current POSIX argument about dirent.h's
unusable structure.  Since doing anything funny with the structure
would be a compiler error, it would not be necessary to explain
why one shouldn't do funny things with the structure.

====

By the way, PCC and GCC both compile this and print "4".
i.e. they treat an undefined structure as having zero size.
Sounds both useless and dangerous to me.

    struct s;
    struct {
        int x;
        struct s;
    } z;
    
    main() {
        printf("%d\n", sizeof(z));
    }



More information about the Comp.lang.c mailing list