Connect with us

Difference between union and structure

Discussion in 'Microcontrollers, Programming and IoT' started by anukalp, Oct 6, 2018.

  1. anukalp

    anukalp

    14
    0
    Jul 28, 2018
    I've been searching on internet and trying to understand how union is different then structure in c language

    structure is use to hold different type of data type

    Code:
    #include <stdio.h>
    
    struct student{
        char *name;
        int age;
    }record;
    int main()
    {
        
         record.name = "Ceena";
         record.age = 35;
    
         printf("student name : %s", record.name);
         printf("\nStudent Age: %d", record.age);
        
     return 0;
    }
    In this link https://www.geeksforgeeks.org/difference-structure-union-c/ there are the six reason I don't understand second reason memory allocation for union and structure

    Can anyone help me to understand how union is different then structure in c language ?
     
  2. (*steve*)

    (*steve*) ¡sǝpodᴉʇuɐ ǝɥʇ ɹɐǝɥd Moderator

    24,860
    2,571
    Jan 21, 2010
    In a struct the variables all occupy their own place in memory. In a union they all overlap.
     
    anukalp likes this.
  3. anukalp

    anukalp

    14
    0
    Jul 28, 2018
    can you explain little bit how they will overlap ?
     
  4. (*steve*)

    (*steve*) ¡sǝpodᴉʇuɐ ǝɥʇ ɹɐǝɥd Moderator

    24,860
    2,571
    Jan 21, 2010
    They will occupy the same memory locations.
     
  5. anukalp

    anukalp

    14
    0
    Jul 28, 2018
    Example for structure

    Code:
    struct student{
        int roll_number;
        float mark ;
    }record;
    A struct will allocate space in memory for each of it's members at same time

    0001 for int
    0002 for float


    Example for union

    Code:
    union student{
        int roll_number;
        float mark ;
    }record;
    A union will use the same space in memory for each of it's members

    A union will allocate space in memory for any one of it's members at one time

    first it will allocate memory space 0001 for int and later it will use same memory space 0001 for float

    Does it happen ?
     
  6. (*steve*)

    (*steve*) ¡sǝpodᴉʇuɐ ǝɥʇ ɹɐǝɥd Moderator

    24,860
    2,571
    Jan 21, 2010
    Not later, at the same time. All variables are always available.

    Your code might use this to save space in certain cases. In my experience it is more often used to overlay structures which may contain different data at different times.

    For example a set of 4 byres might contain one long integer or 4 separate bytes depending on context. An old style ip address is often presented this way.
     
  7. anukalp

    anukalp

    14
    0
    Jul 28, 2018
    I didn't understand

    consider example

    Code:
    union student{
        int roll_number;
        float mark ;
    }record;
    memory space
    0001
    0002
    0003
    0004
    .......

    0010

    how the union will allocate memory space ?
     
  8. (*steve*)

    (*steve*) ¡sǝpodᴉʇuɐ ǝɥʇ ɹɐǝɥd Moderator

    24,860
    2,571
    Jan 21, 2010
    both variables will start at the same location in memory. The size of the union will be that of the largest member.
     
  9. Harald Kapp

    Harald Kapp Moderator Moderator

    8,687
    1,691
    Nov 17, 2011
    Here's a good description of unions in C including an example what can go wrong when a union is handled without the required care.
     
  10. (*steve*)

    (*steve*) ¡sǝpodᴉʇuɐ ǝɥʇ ɹɐǝɥd Moderator

    24,860
    2,571
    Jan 21, 2010
    Unfortunately that sure contains the rather misleading information:

    "You can define a union with many members, but only one member can contain a value at any given time"

    Because the variables occupy the same memory, placing a value in one will generally place a value in all of them. However, there is no guarantee that the other fields will contain meaningful or even valid data.
     
  11. anukalp

    anukalp

    14
    0
    Jul 28, 2018
    I had asked you before, I thought you would explain by giving examples.

    I still do not understand, can you explain by giving examples,
     
  12. (*steve*)

    (*steve*) ¡sǝpodᴉʇuɐ ǝɥʇ ɹɐǝɥd Moderator

    24,860
    2,571
    Jan 21, 2010
    No. You need to learn yourself.

    Implement something yourself and see what happens.

    I'd recommend unioning together an integer and a byte.

    Put values into one and see what happens to the other.

    To understand this you need to understand the size and the layout of data types on your machine. Do you have this basic understanding?
     
  13. anukalp

    anukalp

    14
    0
    Jul 28, 2018
    look post 7, didn't I try to do that ?

    sizeof gives the size of a variable

    Code:
    #include<stdio.h>
    int main()
    {
        printf("%d\n",sizeof(char));
        printf("%d\n",sizeof(int));
        printf("%d\n",sizeof(float));
        printf("%d", sizeof(double));
        return 0;
    } 
    output 1 4 4 and 8

    Machine take 1 byte to store character
    Machine take 4 byte to store integer value
    Machine take 4 byte to store float value
    Machine take 8 byte to store big data
     
  14. (*steve*)

    (*steve*) ¡sǝpodᴉʇuɐ ǝɥʇ ɹɐǝɥd Moderator

    24,860
    2,571
    Jan 21, 2010
    But what exactly is stored in those bytes?

    If you set your integer to -75, what would the character be?

    Similarly, if you set the integer to zero, then placed an "A" in the character variable, what value would the integer have?

    You need to know this if you're using unions in one particular way.

    If all you want to do is save space, and you know that you can't use the variables at the same time, then this information isn't necessary.
     
  15. anukalp

    anukalp

    14
    0
    Jul 28, 2018
    I am more confused by you're answer
     
  16. (*steve*)

    (*steve*) ¡sǝpodᴉʇuɐ ǝɥʇ ɹɐǝɥd Moderator

    24,860
    2,571
    Jan 21, 2010
    Ok. I'll stop then.
     
  17. Harald Kapp

    Harald Kapp Moderator Moderator

    8,687
    1,691
    Nov 17, 2011
    According to post #13 both integer or float occupy 4 bytes. Assume your memory is 8 bit wide and the starting address of the union is 0x0001. This then means addresses 0x0001 to 0x0003 will be used to store the value of roll_number or mark. Note that both variables occupy the exact same addresses!
    When you access the union using the syntax record.roll_number the content of memory addresses 0x001 to 0x003 wil be interpreted as an integer number.
    When you access the union using the syntax record.mark the content of memory addresses 0x001 to 0x003 wil be interpreted as a float number.
    This may (and typically will) lead to unpredictable behavior of a program if the program(mer) doesn't take care to evaluate the contents of a union in the right context. Read the link in my post #9.

    A general computer is not aware of data types. Memory content is just a sequence of bits and bytes. It is a matter of interpretation what you make of these. A byte with hex value 0x41 may represent for example:

    • an integer number 65 (decimal)
    • an ASCII character ('A')
    • a set of bits (1000 0001)
    • or whatever you define it to represent.

    Therefore mixing data types in a union requires careful handling. When you put a float number into your union record (record.mark), you should not access it as a record.roll_number as the sequence of bits found there may make no sense at all when interpreted as an integer. And vice versa.
     
    WHYSguy likes this.
  18. anukalp

    anukalp

    14
    0
    Jul 28, 2018
    I didn't mean that,

    int integer = 0;
    char character = 'A'

    character variable take 1 byte to store 'A' in memory
    integer take 4 byte to store integer value 0 in memory

    Each has different size to store their value

    They will occupy the same memory location ?
     
  19. (*steve*)

    (*steve*) ¡sǝpodᴉʇuɐ ǝɥʇ ɹɐǝɥd Moderator

    24,860
    2,571
    Jan 21, 2010
    @Harald Kapp I think you mean memory locations x0001 to x0004. Also it may be important if the machine is big big endian, little little endian, big little endian or little big endian for longs as to which byte is first.

    @anukalp my explanations are not helping you. I do not wish to confuse you further. Perhaps someone else can put things a way that works for you.
     
  20. gorgon

    gorgon

    599
    22
    Jun 6, 2011
    Did you read this description? From what you write, I don't think you did.
    This text explains very good all sides of the 'union' problem. You could test this out yourself from the examples given.
    You should also read about, and test how the 'structure' declaration works to understand the difference.

    When starting to learn C, 'union' is not the first declaration to use. Depending on what program types you do, you may never need it at all.
     
    Harald Kapp likes this.
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 (here). After that, you can post your question and our members will help you out.