martin wrote:
I want to initiate a union and and have the problem that I sometimes
need to use float and sometimes an int. The float values (u.fval) turns
up ok but not the ints (u.ival).
I tried typecating it as below but it does not seem to do the trick.
Would be happy if anyone has a solution for this problem.
struct str {
int i;
float f;
typedef union {
float fval;
int ival;
} u;
} tStruct;
The above is hopelessly mangled. See the example below.
tStruct structArray[] = {
{ 0, 0.0 , 3.2},
{ 0, 0.0 , (float)(int)9}
};
Here is a C99-oriented way to do this:
#include <stdio.h>
typedef struct
{
int i;
float f;
union
{
float fval;
int ival;
} u;
} tStruct;
int main(void)
{
tStruct structArray[] = {
{.u.fval = 3.2},
{.u.ival = 9}
};
printf("structArray[0].u.fval contains %g, expected 3.2\n",
structArray[0].u.fval);
printf("structArray[1].u.ival contains %d, expected 9\n",
structArray[1].u.ival);
return 0;
}
[output]
structArray[0].u.fval contains 3.2, expected 3.2
structArray[1].u.ival contains 9, expected 9