Re: Defining a union

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



lchaplin13@xxxxxxxxx wrote:
Hi all,
I would like to convert the following C code into C#, any help will be
greatly appreciated:

union real{
int n;
float x;
} answer1;

union realdouble{
int n[2];
double x;
} answer2;

I've tried already
[StructLayout(LayoutKind.Explicit)]
public struct Real
{
[FieldOffset(0)]public int n;
[FieldOffset(0)]public float x;
}
but I get the error "Use of possibly unassigned field 'n' (CS0170)"
Real answer1;
answer1.x = inputValue;
Console.Write("Real Value = {0} \n", answer1.n);
For the second union I don't have a clue...

Thanks,
Lee

The reason that you get that error is that the field is unassigned. The compiler doesn't take in account that the field occupies (partly or completely) the same memory area as another field.

To make the second struct work you would also have to use attributes to make an inline array. I don't remembter exactly how that is done.

How about scrapping the structs altogether and use the GetBytes, ToSingle and ToDouble methods of the BitConverter class?

--
Göran Andersson
_____
http://www.guffa.com
.



Relevant Pages

  • Re: Pointer to "base" type - what does the Standard say about this?
    ... One such exception is to access equivalent initial members of structs ... that are union members. ... Don't make the base type a struct member, ... struct s {int i; const int ci;}; ...
    (comp.lang.c)
  • gcc, aliasing rules and unions
    ... struct B {int x, y;}; ... A struct pointer can be converted to another ... Also I don't know what the "effective type" of a union member is. ...
    (comp.lang.c)
  • Re: problem with cast and unions
    ... The part where there is that problem is about conversion from a C float ... to a Small "cell" (actually an int). ... structure, and even then, only if it was NOT the member most recently ... need to declare the union. ...
    (comp.lang.c)
  • Re: Error freeing memory....
    ... int pvarid; ... float *mean; ... struct AR { ... void USAGE; ...
    (comp.lang.c)
  • Re: Is this legal ?
    ... I wanted to have a union which has two structures in it. ... b.c:10: warning: ANSI C forbids member declarations with no members ...
    (comp.lang.c)