Initiate a union

M

martin

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;

tStruct structArray[] = {
{ 0, 0.0 , 3.2},
{ 0, 0.0 , (float)(int)9}
};
 
M

Martin Ambuhl

martin said:
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
 
U

usr.root

gladiator 写é“:
If we want to initialize i, f and union u ?
How to do that


you can do it like this
tStruct structArray[] = {
{1,2.3,.u.fval = 3.2},
{2,3,4,.u.ival = 9}
};
i have test it!
 
M

martin

Thanks for the quick response but when I tried your solution my
compiler gave me the following error:

Serious error: <expression> expected but found '.'
 
D

Default User

martin said:
Thanks for the quick response but when I tried your solution my
compiler gave me the following error:

See below. You also failed to show us what you actually tried. We have
not idea what didn't work.



Brian
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,216
Latest member
topweb3twitterchannels

Latest Threads

Top