Thread: Memory allocation in an UNION

  1. #1
    Registered User
    Join Date
    Jan 2010
    Posts
    8

    Memory allocation in an UNION

    We know , in a union memory is allocated for the element having the maximum size.
    So will the following initialization work:

    Code:
    union b
    {
    char ch[2];
    int i;
    };
    int main()
    {
    union b z2={0,2};
    return 0;
    }

  2. #2
    Registered User
    Join Date
    Mar 2009
    Posts
    399
    No, but you can use something like this:
    Code:
    union b z2 = { .ch = {0, 2} }
    EDIT: It seems to be working, had a typo.
    Last edited by Memloop; 06-13-2010 at 07:34 PM.

  3. #3
    Registered User
    Join Date
    Jan 2010
    Posts
    8
    @Memloop

    Code:
    union b z2 = { .ch = {0, 2} }
    What does the above code do exactly?
    Does it initialize ch to 0 and i to 2??

  4. #4
    Registered User
    Join Date
    Mar 2009
    Posts
    399
    Yes.

  5. #5
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    No it doesn't. It initialises z2.ch[0] to 0 (zero) and z2.ch[1] to 2.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  6. #6
    Registered User
    Join Date
    Mar 2009
    Posts
    399
    I misread it as "initialize ch to 0 and 2".

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > So will the following initialization work:
    It should do - did you try it?

    I believe memloop's answer requires a C99 compiler to work.

    Prior to C99, you could only initialise the first named member of the union.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with custom dynamic memory allocation routines
    By BLauritson in forum C++ Programming
    Replies: 12
    Last Post: 03-11-2010, 07:26 AM
  2. Bug in Best-Fit Memory Allocation program (Simulation)
    By RommelTJ in forum C Programming
    Replies: 6
    Last Post: 12-13-2009, 04:43 PM
  3. Understanding Memory Allocation
    By Ragsdale85 in forum C Programming
    Replies: 7
    Last Post: 10-31-2005, 08:36 AM
  4. Windows Memory Allocation :: C++
    By kuphryn in forum Windows Programming
    Replies: 2
    Last Post: 11-03-2002, 12:13 PM
  5. Is it necessary to write a specific memory manager ?
    By Morglum in forum Game Programming
    Replies: 18
    Last Post: 07-01-2002, 01:41 PM