structure

In the mean time we see how to declare a large number of variable of same data type by array. Now we see how to define different data types in a single variable name. We can do this by structure.

A structure can be imagined as a packet of different data type under a single name.

Syntax:

Here struct is a keyword.struct-name is as like as variable name. varible1,varible2,varible3,varible4 is under tag-name variable1 can be accessed as follows:
tag-name.variable1;

Code example:

output

Enter roll: 61
Enter mark : 45

Your input details:
Name: Sattar
Roll: 61
Mark: 45.000000

Union

union is exactly same as structure. union keyword is used instead of struct keyword.Now question may arise – what is the difference between structure and union?

Short cut answer is: The deference is in memory allocation.
Explanation: 
In structure, memory space will be created for all members inside structure. An additional padding byte will be added for smaller memory to perfectly align with the longest memory.
In union memory space will be created only for a member which needs largest memory space.
Consider the following code:

Here there are two members inside struct and union: int and long int.  Memory space for int is: 4 byte and Memory space for long int is: 8.

So for struct 4+8=12 bytes will be created while 8 bytes will be created for union. This memory allocation can be imagined as follows:

Memory Allocation For struct

a(4 byte)
padding(4 byte)
b (8 byte)

Memory Allocation For union

b (8 byte)

So, actually memory allocation for struct is: 4 byte for ‘a’ + 4 padding byte for align with ‘b’  + 8 byte for ‘b’ = 16 byte

Now we modify the struct as follows:

Now Memory Allocation For struct is:

a(4 byte)
b(4 byte)
c (8 byte)

Code example:

output

Memory allocation for structure = 16
Memory allocation for union = 8


Next Previous