Re: Unions and Structure Questions

From: Barry Schwarz (schwarzb_at_deloz.net)
Date: 01/18/04


Date: 17 Jan 2004 23:07:50 GMT

On Sat, 17 Jan 2004 06:49:00 GMT, "kazack" <gadgetsnsuch@talon.net>
wrote:

>A union is the same as a structure with the exception that a union can only
>use one item where a structure can use all?
>
>Example:
>
>int account
>string fname
>string lname
>string phone
>
>A structure uses all of the above where a union can only use one of the
>above at a time?
>
>If I am wrong please correct me, also why would one want to use a union over
>a structure and is it actually pratical to do so?
>
In a union, all the members overlap. Each member of a union has the
same starting address, which is the same as the starting address of
the union itself.

In a struct, none of the members overlap. The members of the struct
are arranged in memory in the same order they are declared in the
struct. The first member will have the same starting address as the
struct itself but there may be padding between members and after the
last member.

<<Remove the del for email>>



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)
  • Re: Global (non _KERNEL) place for sockaddr_union?
    ... The problem is that the definition of the union depends on what you wish ... and which address families are visible to the application ... You may find that such a definition has to have conditionalized members. ... type 'struct sockaddr_storage' if it's to support all address families ...
    (freebsd-arch)
  • Re: Global (non _KERNEL) place for sockaddr_union?
    ... The problem is that the definition of the union depends on what you wish ... and which address families are visible to the application ... You may find that such a definition has to have conditionalized members. ... type 'struct sockaddr_storage' if it's to support all address families ...
    (freebsd-hackers)
  • Re: Global (non _KERNEL) place for sockaddr_union?
    ... The problem is that the definition of the union depends on what you wish ... and which address families are visible to the application ... You may find that such a definition has to have conditionalized members. ... type 'struct sockaddr_storage' if it's to support all address families ...
    (freebsd-net)
  • Re: Unions in C Sharp
    ... In this case you need to marshall the number as Explicit but the string as ... > typedef union ChannelProtocol { ... > struct { ... >>> functions in an unmanaged DLL that has a struct with unions in it as a ...
    (microsoft.public.dotnet.languages.csharp)