bryant%ced.utah.edu@cs.utah.edu (Bryant Eastham) (06/21/91)
I'll start off by saying that before submitting this article I read
the sections in H&S on pointers and initializers, and also wrote a small
program to test this out which compiled without warnings (gcc -Wall -ansi).
The question is the following. I have a structure which will consist
of 3 fields. This structure comes in two flavors, the first uses
the first field as an integer flag, the second as a const char const *
and does not use the third field, while the second flavor uses the first
field as an integer flag, the second as a const STRUCT const * and uses
the third to store an integer. I want to have an array of these structures
initialized at compile-time.
The obvious solution would be to use a union instead of a structure, but
that would require changing quite a bit of code and I don't know that it
would save me anything in the initialization area. Another solution
would be to use a void * as the second element type and cast the value
whenever I use it. This would result in the following code:
typedef struct _one
{
....
} One;
typedef struct _test
{
int
flag;
void
*field2;
int
optional;
} Test;
One
firstStructure;
Test
array [] =
{
{ 1, "Test" },
{ 2, "Another Test" },
{ -3, &firstStructure, 5 }
};
Then I would just have to cast array [ i ].field2 using either
(const char const *) or (const STRUCT const *) to extract the data
that I need, based on the flag field.
Does anyone see any problems with this usage of void *? The only thing
that bothers me is that someone reading the code might be confused by
the initialization. I cannot see any rules being broken here, but then
I am not perfect. :-)
Any response would be appreciated. Thanks in advance.
Bryant Eastham
bryant@ced.utah.edu