There are some drawbacks to how structures are sometimes used, and this can be dangerous if you are not thinking about the consequences.
In your example, if you run the function:
void test(void) { struct header; char *p = &header.data[0]; ... }
Then the results are undefined (since no data storage has been allocated). This is something you usually know about, but there are times when C programmers are probably used to use value semantics for structures that break down in various ways.
For example, if I define:
struct header2 { int len; char data[MAXLEN]; }
Then I can copy two instances simply by assignment, that is:
struct header2 inst1 = inst2;
Or, if they are defined as pointers:
struct header2 *inst1 = *inst2;
This, however, will not work, since the array of data variables is not copied. You want to dynamically allocate the size of the structure and copy over the array using memcpy or equivalent.
Similarly, writing a function that takes a structure will not work, since the arguments in the function calls are again copied by value, and therefore what you get is likely to be only the first element of your data array.
This does not make it a bad idea, but you should keep in mind always dynamically allocate these structures and pass them only as pointers.
wds 03 Mar. '14 at 9:31 2014-03-03 09:31
source share