Variable structure size -- ANSI ?

Michael N Johnston id8rld06 at serss0.fiu.edu
Sun Apr 14 17:16:11 AEST 1991


Stephen R. van den Berg writes:
]Michael N Johnston writes:
]]>struct foo {
]]>unsigned short recsize;
]]>unsigned short num;
]]>char info [24];
]]>byte flags;
]]>char filename[1]
]]>};
]]>Where, foo.filename is a placeholder for a variable length string.
]
]]If you plan to store a char array in filename DON'T. Use char *filename
]]and point this to your actual array. Using your origional declaration
]]and doing something like strcpy(foo_ptr->filename, "abcde") will lead
]]to disaster.
]
]Why should this lead to disaster?   Is this not allowed by ANSI?
]If you can make sure that you have malloced more than enough space for the
]structure, shouldn't you be able to use all this space by doing just that?

    Whether it is "permited" by ANSI or not I am not sure. However,
even if it is permited by the standard, it is rather poor coding style.
>From the point of view of maintanance, consider what would happen if
you put the program aside for six months or a year. You are not likely
to remember every coding trick that the program uses when you finally
come back to it. Or say, you give the program to a freind and he (or you)
decides to modify it and adds another field to struct foo after filemane.
All of a sudden, the program stops working. Unless you remember (or he
figures out) that the order of fields in foo is important, there is
going to be a tough debugging session ahead.
    A much more maintainable way to accomplish the same thing is to use
char *filename and do structname.filename = malloc(...). Since you plan
to malloc storage for the struct this would mean two calls to malloc,
but the benefits would almost always outway the cost. Doing this makes
it clear that filename is pointing to an array rather than just being
a one character array.
    C makes several quick coding tricks easy but unless you are just
doing a one time "quick and dirty" program, they should generally be
avoided. OFTEN using them makes even a small program nearly
unmaintainable. Sometimes, they can really be helpful, but, this is
the exception and not the rule.

Mike
--
====================================================================
Michael Johnston
id8rld06 at serss0.fiu.edu or
26793271x at servax.fiu.edu



More information about the Comp.lang.c mailing list